From 49bbd872d57240d9e67e5d53a40800d8c3c2238f Mon Sep 17 00:00:00 2001 From: Mark Paluch Date: Mon, 23 Jan 2017 20:04:16 +0100 Subject: [PATCH] DATACASS-389 - Java 8 cleanup. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add deprecations. Remove unused classes. Replace explicit type arguments with diamond operator. Replace imperative for-loops with stream/forEach (functional approach). Replace anonymous inner classes with lambdas. Replace with {@code}. --- .../CassandraCqlClusterFactoryBean.java | 74 ++++------ .../CassandraCqlSessionFactoryBean.java | 78 ++++++---- .../CassandraCqlTemplateFactoryBean.java | 24 ++- .../config/DataCenterReplication.java | 45 +++++- .../cassandra/config/KeyspaceAction.java | 12 +- ...eyspaceActionSpecificationFactoryBean.java | 36 +++-- .../cassandra/config/KeyspaceAttributes.java | 15 +- .../MultiLevelListFlattenerFactoryBean.java | 23 +-- .../MultiLevelSetFlattenerFactoryBean.java | 25 ++-- .../config/PoolingOptionsFactoryBean.java | 98 ++++++------- .../config/SocketOptionsFactoryBean.java | 18 ++- .../config/xml/CassandraCqlClusterParser.java | 21 +-- .../config/xml/DefaultCqlBeanNames.java | 6 +- .../cassandra/config/xml/ParsingUtils.java | 28 ++-- .../core/ArgumentPreparedStatementBinder.java | 3 + .../cassandra/core/AsyncCqlTemplate.java | 40 +++-- .../core/AsynchronousQueryListener.java | 14 +- .../core/CachedPreparedStatementCreator.java | 14 +- .../cassandra/core/ColumnMapRowMapper.java | 6 +- .../cassandra/core/CqlTemplate.java | 4 +- ...ionTranslatingListenableFutureAdapter.java | 18 +-- .../core/GuavaListenableFutureAdapter.java | 21 +-- .../cassandra/core/Ordering.java | 16 +- .../core/PreparedStatementBinder.java | 13 +- .../core/PreparedStatementCallback.java | 5 +- .../core/PreparedStatementCreator.java | 1 - .../cassandra/core/PrimaryKeyType.java | 4 +- .../cassandra/core/QueryForListListener.java | 19 ++- .../core/QueryForListOfMapListener.java | 19 ++- .../cassandra/core/QueryForMapListener.java | 19 ++- .../core/QueryForObjectListener.java | 10 +- .../cassandra/core/ReactiveCqlTemplate.java | 25 +++- .../cassandra/core/ResultSetExtractor.java | 5 +- .../core/ResultSetFutureCancellable.java | 37 ----- .../core/ResultSetFutureExtractor.java | 10 +- .../cassandra/core/RingMember.java | 54 +++++-- .../cassandra/core/RingMemberHostMapper.java | 6 +- .../cassandra/core/RowCallback.java | 17 ++- .../cassandra/core/RowCallbackHandler.java | 1 - .../cassandra/core/RowIterator.java | 8 +- .../cassandra/core/RowMapper.java | 1 - .../cassandra/core/SessionCallback.java | 9 +- .../core/SimplePreparedStatementCreator.java | 37 +++-- .../cassandra/core/SingleColumnRowMapper.java | 4 + .../converter/AbstractResultSetConverter.java | 17 ++- ...actResultSetToBasicFixedTypeConverter.java | 17 ++- .../converter/ResultSetToArrayConverter.java | 2 +- .../ResultSetToBigDecimalConverter.java | 21 +++ .../ResultSetToBigIntegerConverter.java | 21 +++ .../ResultSetToBooleanConverter.java | 21 +++ .../ResultSetToByteBufferConverter.java | 21 +++ .../converter/ResultSetToDateConverter.java | 21 +++ .../converter/ResultSetToDoubleConverter.java | 21 +++ .../converter/ResultSetToFloatConverter.java | 21 +++ .../ResultSetToInetAddressConverter.java | 21 +++ .../ResultSetToIntegerConverter.java | 21 +++ .../converter/ResultSetToListConverter.java | 2 +- .../ResultSetToListOfStringConverter.java | 44 +++--- .../converter/ResultSetToLongConverter.java | 21 +++ .../converter/ResultSetToStringConverter.java | 21 +++ .../converter/ResultSetToUuidConverter.java | 21 +++ .../core/converter/RowToArrayConverter.java | 18 +++ .../core/converter/RowToListConverter.java | 18 +-- .../core/converter/RowToMapConverter.java | 15 +- .../cassandra/core/cql/CqlConstantType.java | 17 ++- .../cassandra/core/cql/CqlIdentifier.java | 19 ++- .../cassandra/core/cql/CqlStringUtils.java | 30 ++-- .../core/cql/KeyspaceIdentifier.java | 5 +- .../generator/AlterColumnCqlGenerator.java | 6 +- .../generator/AlterKeyspaceCqlGenerator.java | 14 +- .../generator/CreateIndexCqlGenerator.java | 15 +- .../generator/CreateKeyspaceCqlGenerator.java | 14 +- .../generator/CreateTableCqlGenerator.java | 21 ++- .../cql/generator/DropIndexCqlGenerator.java | 14 +- .../generator/DropKeyspaceCqlGenerator.java | 14 +- .../cql/generator/DropTableCqlGenerator.java | 14 +- .../keyspace/AlterTableSpecification.java | 4 +- .../keyspace/AlterUserTypeSpecification.java | 4 +- .../core/keyspace/ColumnSpecification.java | 16 +- .../keyspace/CreateIndexSpecification.java | 6 +- .../keyspace/CreateKeyspaceSpecification.java | 19 ++- .../keyspace/CreateTableSpecification.java | 20 +-- .../core/keyspace/DropIndexSpecification.java | 12 +- .../core/keyspace/DropTableSpecification.java | 22 ++- .../core/keyspace/KeyspaceOption.java | 14 +- .../KeyspaceOptionsSpecification.java | 31 ++-- .../cassandra/core/keyspace/Option.java | 17 +-- .../core/keyspace/TableDescriptor.java | 18 +-- .../cassandra/core/keyspace/TableOption.java | 82 +++++------ .../keyspace/TableOptionsSpecification.java | 31 ++-- .../core/keyspace/TableSpecification.java | 10 +- .../core/keyspace/UserTypeSpecification.java | 4 +- .../core/session/ReactiveResultSet.java | 6 +- .../core/support/EmptyResultSet.java | 121 --------------- .../core/support/ResultSetAdapter.java | 137 ----------------- .../cassandra/core/util/CollectionUtils.java | 56 ------- .../cassandra/core/util/MapBuilder.java | 106 ++++++++++---- .../cassandra/support/CassandraAccessor.java | 10 +- .../CassandraConnectionFailureException.java | 12 +- ...CassandraSchemaElementExistsException.java | 14 +- ...ssandraCqlSessionFactoryBeanUnitTests.java | 4 +- .../PoolingOptionsFactoryBeanUnitTests.java | 2 +- .../AsyncCqlTemplateIntegrationTests.java | 4 +- .../core/AsyncCqlTemplateUnitTests.java | 8 +- .../ConsistencyLevelResolverUnitTests.java | 6 +- .../core/CqlTemplateIntegrationTests.java | 2 +- .../core/SingleColumnRowMapperUnitTests.java | 2 +- .../AlterKeyspaceCqlGeneratorUnitTests.java | 9 +- ...lterTableCqlGeneratorIntegrationTests.java | 2 +- .../AlterTableCqlGeneratorUnitTests.java | 2 +- .../CreateKeyspaceCqlGeneratorUnitTests.java | 2 +- .../CreateTableCqlGeneratorUnitTests.java | 16 +- .../core/support/EmptyResultSetUnitTests.java | 105 ------------- .../core/util/CollectionUtilsUnitTests.java | 138 ------------------ ...tractEmbeddedCassandraIntegrationTest.java | 12 +- ...stractKeyspaceCreatingIntegrationTest.java | 14 +- .../test/integration/CassandraRule.java | 29 ++-- .../EmbeddedCassandraServerHelper.java | 22 +-- .../test/integration/KeyspaceRule.java | 11 +- .../java/KeyspaceCreatingJavaConfig.java | 2 +- .../CassandraConnectionProperties.java | 18 +-- .../data/cassandra/Constants.java | 23 --- .../config/BeanDefinitionBuilderArgument.java | 18 +-- .../cassandra/config/BeanDefinitionUtils.java | 38 +++-- .../config/CassandraEntityClassScanner.java | 26 ++-- .../cassandra/config/DefaultBeanNames.java | 7 +- .../data/cassandra/config/SchemaAction.java | 12 +- .../xml/CassandraMappingContextParser.java | 8 +- .../convert/CassandraConverters.java | 6 +- .../convert/CassandraJodaTimeConverters.java | 4 +- .../convert/CassandraJsr310Converters.java | 2 +- .../CassandraThreeTenBackPortConverters.java | 4 +- .../cassandra/convert/CustomConversions.java | 6 +- .../convert/MappingCassandraConverter.java | 9 +- .../core/CassandraAdminOperations.java | 7 +- .../cassandra/core/CassandraTemplate.java | 17 ++- .../data/cassandra/core/CassandraValue.java | 10 +- .../data/cassandra/core/DeletionListener.java | 8 + .../data/cassandra/core/WriteListener.java | 12 +- .../mapping/BasicCassandraMappingContext.java | 27 +--- .../BasicCassandraPersistentEntity.java | 2 +- .../BasicCassandraPersistentProperty.java | 18 +-- .../mapping/CassandraPersistentProperty.java | 2 +- .../mapping/CassandraSimpleTypeHolder.java | 24 +-- .../data/cassandra/mapping/EntityMapping.java | 4 +- .../data/cassandra/mapping/Mapping.java | 10 +- .../data/cassandra/mapping/PrimaryKey.java | 6 +- ...PrimaryKeyClassEntityMetadataVerifier.java | 12 +- .../mapping/VerifierMappingExceptions.java | 15 +- .../data/cassandra/repository/MapId.java | 23 ++- .../cdi/CassandraRepositoryExtension.java | 14 +- ...andraRepositoryConfigurationExtension.java | 33 +++-- ...andraRepositoryConfigurationExtension.java | 16 +- .../query/AbstractCassandraQuery.java | 6 +- .../query/CassandraQueryCreator.java | 4 +- .../query/CassandraQueryMethod.java | 4 +- .../ExpressionEvaluatingParameterBinder.java | 11 +- .../repository/query/StringBasedQuery.java | 6 +- .../support/CassandraRepositoryFactory.java | 2 +- .../support/IdInterfaceExceptions.java | 19 +-- .../support/IdInterfaceValidator.java | 31 +++- .../support/MapIdProxyDelegate.java | 44 ++++-- .../support/SimpleCassandraRepository.java | 9 +- .../data/cassandra/util/CqlUtils.java | 73 +++++---- .../data/cassandra/RowMockUtil.java | 74 +++------- .../CassandraSessionFactoryBeanUnitTests.java | 24 +-- .../config/SchemaActionIntegrationTests.java | 55 +++---- .../CassandraTypeMappingIntegrationTest.java | 8 +- .../CustomConversionIntegrationTests.java | 2 +- .../convert/CustomConversionsUnitTests.java | 20 +-- .../MappingCassandraConverterUnitTests.java | 30 ++-- .../core/AsyncCassandraTemplateUnitTests.java | 4 +- ...ersistentEntitySchemaCreatorUnitTests.java | 16 +- ...ersistentEntitySchemaDropperUnitTests.java | 14 +- .../CassandraTemplateIntegrationTests.java | 4 +- ...BasicCassandraMappingContextUnitTests.java | 16 +- ...sistentEntityOrderPropertiesUnitTests.java | 22 +-- ...sicCassandraPersistentEntityUnitTests.java | 16 +- ...cCassandraPersistentPropertyUnitTests.java | 2 +- ...CassandraCompositePrimaryKeyUnitTests.java | 4 +- ...ndraUserTypePersistentEntityUnitTests.java | 4 +- .../mapping/CompoundPrimaryKeyUnitTests.java | 4 +- ...BasicCassandraMappingContextUnitTests.java | 40 +++-- .../ForceQuotedEntitiesSimpleUnitTests.java | 6 +- .../MultipackageScanningUnitTests.java | 6 +- ...aParametersParameterAccessorUnitTests.java | 10 +- .../ParameterBindingParserUnitTests.java | 12 +- .../PartTreeCassandraQueryUnitTests.java | 2 +- .../StringBasedCassandraQueryUnitTests.java | 2 +- .../support/BasicMapIdUnitTests.java | 2 +- ...veCassandraRepositoryIntegrationTests.java | 4 +- ...tionsRowValueProviderIntegrationTests.java | 6 +- .../CompositeKeyCrudIntegrationTests.java | 4 +- .../entity/CorrelationEntity.java | 10 +- .../UserRepositoryIntegrationTests.java | 2 +- .../integration/simpletons/BookCondition.java | 2 +- ...gDataEmbeddedCassandraIntegrationTest.java | 11 +- .../support/IntegrationTestConfig.java | 6 +- .../integration/support/SchemaTestUtils.java | 24 ++- 199 files changed, 1789 insertions(+), 2004 deletions(-) delete mode 100644 spring-cql/src/main/java/org/springframework/cassandra/core/ResultSetFutureCancellable.java delete mode 100644 spring-cql/src/main/java/org/springframework/cassandra/core/support/EmptyResultSet.java delete mode 100644 spring-cql/src/main/java/org/springframework/cassandra/core/support/ResultSetAdapter.java delete mode 100644 spring-cql/src/main/java/org/springframework/cassandra/core/util/CollectionUtils.java delete mode 100644 spring-cql/src/test/java/org/springframework/cassandra/core/support/EmptyResultSetUnitTests.java delete mode 100755 spring-cql/src/test/java/org/springframework/cassandra/core/util/CollectionUtilsUnitTests.java delete mode 100644 spring-data-cassandra/src/main/java/org/springframework/data/cassandra/Constants.java diff --git a/spring-cql/src/main/java/org/springframework/cassandra/config/CassandraCqlClusterFactoryBean.java b/spring-cql/src/main/java/org/springframework/cassandra/config/CassandraCqlClusterFactoryBean.java index 14da7ecdb..6487509f6 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/config/CassandraCqlClusterFactoryBean.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/config/CassandraCqlClusterFactoryBean.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2016 the original author or authors. + * Copyright 2013-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,25 +32,14 @@ import org.springframework.cassandra.core.cql.generator.DropKeyspaceCqlGenerator import org.springframework.cassandra.core.keyspace.CreateKeyspaceSpecification; import org.springframework.cassandra.core.keyspace.DropKeyspaceSpecification; import org.springframework.cassandra.core.keyspace.KeyspaceActionSpecification; -import org.springframework.cassandra.core.util.CollectionUtils; import org.springframework.cassandra.support.CassandraExceptionTranslator; import org.springframework.dao.DataAccessException; import org.springframework.dao.support.PersistenceExceptionTranslator; import org.springframework.util.Assert; +import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; -import com.datastax.driver.core.AuthProvider; -import com.datastax.driver.core.Cluster; -import com.datastax.driver.core.Host; -import com.datastax.driver.core.LatencyTracker; -import com.datastax.driver.core.NettyOptions; -import com.datastax.driver.core.PoolingOptions; -import com.datastax.driver.core.ProtocolVersion; -import com.datastax.driver.core.QueryOptions; -import com.datastax.driver.core.SSLOptions; -import com.datastax.driver.core.Session; -import com.datastax.driver.core.SocketOptions; -import com.datastax.driver.core.TimestampGenerator; +import com.datastax.driver.core.*; import com.datastax.driver.core.Cluster.Builder; import com.datastax.driver.core.ProtocolOptions.Compression; import com.datastax.driver.core.policies.AddressTranslator; @@ -76,8 +65,8 @@ import com.datastax.driver.core.policies.SpeculativeExecutionPolicy; * @see com.datastax.driver.core.Cluster */ @SuppressWarnings("unused") -public class CassandraCqlClusterFactoryBean implements FactoryBean, InitializingBean, DisposableBean, - BeanNameAware, PersistenceExceptionTranslator { +public class CassandraCqlClusterFactoryBean + implements FactoryBean, InitializingBean, DisposableBean, BeanNameAware, PersistenceExceptionTranslator { public static final boolean DEFAULT_JMX_REPORTING_ENABLED = true; public static final boolean DEFAULT_METRICS_ENABLED = true; @@ -108,12 +97,12 @@ public class CassandraCqlClusterFactoryBean implements FactoryBean, Ini private Host.StateListener hostStateListener; private LatencyTracker latencyTracker; - private List keyspaceCreations = new ArrayList(); - private List keyspaceDrops = new ArrayList(); - private Set> keyspaceSpecifications = new HashSet>(); + private List keyspaceCreations = new ArrayList<>(); + private List keyspaceDrops = new ArrayList<>(); + private Set> keyspaceSpecifications = new HashSet<>(); - private List startupScripts = new ArrayList(); - private List shutdownScripts = new ArrayList(); + private List startupScripts = new ArrayList<>(); + private List shutdownScripts = new ArrayList<>(); private LoadBalancingPolicy loadBalancingPolicy; private NettyOptions nettyOptions; @@ -307,16 +296,15 @@ public class CassandraCqlClusterFactoryBean implements FactoryBean, Ini */ private void generateSpecificationsFromFactoryBeans() { - for (KeyspaceActionSpecification keyspaceSpecification : keyspaceSpecifications) { - - if (keyspaceSpecification instanceof CreateKeyspaceSpecification) { - keyspaceCreations.add((CreateKeyspaceSpecification) keyspaceSpecification); + keyspaceSpecifications.forEach(keyspaceActionSpecification -> { + if (keyspaceActionSpecification instanceof CreateKeyspaceSpecification) { + keyspaceCreations.add((CreateKeyspaceSpecification) keyspaceActionSpecification); } - if (keyspaceSpecification instanceof DropKeyspaceSpecification) { - keyspaceDrops.add((DropKeyspaceSpecification) keyspaceSpecification); + if (keyspaceActionSpecification instanceof DropKeyspaceSpecification) { + keyspaceDrops.add((DropKeyspaceSpecification) keyspaceActionSpecification); } - } + }); } protected void executeSpecsAndScripts(List> kepspaceActionSpecifications, @@ -329,13 +317,10 @@ public class CassandraCqlClusterFactoryBean implements FactoryBean, Ini try { CqlTemplate template = new CqlTemplate(session); - for (KeyspaceActionSpecification keyspaceActionSpecification : kepspaceActionSpecifications) { - template.execute(toCql(keyspaceActionSpecification)); - } + kepspaceActionSpecifications + .forEach(keyspaceActionSpecification -> template.execute(toCql(keyspaceActionSpecification))); - for (String script : scripts) { - template.execute(script); - } + scripts.forEach(template::execute); } finally { if (session != null) { session.close(); @@ -347,8 +332,8 @@ public class CassandraCqlClusterFactoryBean implements FactoryBean, Ini private String toCql(KeyspaceActionSpecification keyspaceActionSpecification) { return (keyspaceActionSpecification instanceof CreateKeyspaceSpecification - ? new CreateKeyspaceCqlGenerator((CreateKeyspaceSpecification) keyspaceActionSpecification).toCql() - : new DropKeyspaceCqlGenerator((DropKeyspaceSpecification) keyspaceActionSpecification).toCql()); + ? new CreateKeyspaceCqlGenerator((CreateKeyspaceSpecification) keyspaceActionSpecification).toCql() + : new DropKeyspaceCqlGenerator((DropKeyspaceSpecification) keyspaceActionSpecification).toCql()); } /* @@ -362,8 +347,8 @@ public class CassandraCqlClusterFactoryBean implements FactoryBean, Ini } /** - * Set a comma-delimited string of the contact points (hosts) to connect to. Default is {@code localhost}; - * see {@link #DEFAULT_CONTACT_POINTS}. + * Set a comma-delimited string of the contact points (hosts) to connect to. Default is {@code localhost}; see + * {@link #DEFAULT_CONTACT_POINTS}. * * @param contactPoints the contact points used by the new cluster. */ @@ -528,7 +513,6 @@ public class CassandraCqlClusterFactoryBean implements FactoryBean, Ini } /** - * * @return the startup scripts */ public List getStartupScripts() { @@ -547,7 +531,6 @@ public class CassandraCqlClusterFactoryBean implements FactoryBean, Ini } /** - * * @return the shutdown scripts */ public List getShutdownScripts() { @@ -626,8 +609,8 @@ public class CassandraCqlClusterFactoryBean implements FactoryBean, Ini } /** - * Configures the address translator used by the new cluster to translate IP addresses received - * from Cassandra nodes into locally query-able addresses. + * Configures the address translator used by the new cluster to translate IP addresses received from Cassandra nodes + * into locally query-able addresses. * * @param addressTranslator {@link AddressTranslator} used by the new cluster. * @see com.datastax.driver.core.Cluster.Builder#withAddressTranslator(AddressTranslator) @@ -664,8 +647,8 @@ public class CassandraCqlClusterFactoryBean implements FactoryBean, Ini } /** - * Sets the maximum time to wait for schema agreement before returning from a DDL query. The timeout is used - * to wait for all currently up hosts in the cluster to agree on the schema. + * Sets the maximum time to wait for schema agreement before returning from a DDL query. The timeout is used to wait + * for all currently up hosts in the cluster to agree on the schema. * * @param seconds max schema agreement wait in seconds. * @see com.datastax.driver.core.Cluster.Builder#withMaxSchemaAgreementWaitSeconds(int) @@ -690,8 +673,7 @@ public class CassandraCqlClusterFactoryBean implements FactoryBean, Ini /** * Configures the generator that will produce the client-side timestamp sent with each query. * - * @param timestampGenerator {@link TimestampGenerator} used to produce a client-side timestamp - * sent with each query. + * @param timestampGenerator {@link TimestampGenerator} used to produce a client-side timestamp sent with each query. * @see com.datastax.driver.core.Cluster.Builder#withTimestampGenerator(TimestampGenerator) * @see com.datastax.driver.core.TimestampGenerator * @since 1.5 diff --git a/spring-cql/src/main/java/org/springframework/cassandra/config/CassandraCqlSessionFactoryBean.java b/spring-cql/src/main/java/org/springframework/cassandra/config/CassandraCqlSessionFactoryBean.java index 1e4f5bcf1..cb96c6b5a 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/config/CassandraCqlSessionFactoryBean.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/config/CassandraCqlSessionFactoryBean.java @@ -1,12 +1,12 @@ /* - * Copyright 2013-2014 the original author or authors. - * + * Copyright 2013-2017 the original author or authors. + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. @@ -38,8 +38,8 @@ import com.datastax.driver.core.Cluster; import com.datastax.driver.core.Session; /** - * Factory for creating and configuring a Cassandra {@link Session}, which is a thread-safe singleton. - * As such, it is sufficient to have one {@link Session} per application and keyspace. + * Factory for creating and configuring a Cassandra {@link Session}, which is a thread-safe singleton. As such, it is + * sufficient to have one {@link Session} per application and keyspace. * * @author Alex Shvid * @author Matthew T. Adams @@ -53,80 +53,98 @@ import com.datastax.driver.core.Session; * @see com.datastax.driver.core.Cluster * @see com.datastax.driver.core.Session */ -@SuppressWarnings("unused") -public class CassandraCqlSessionFactoryBean implements FactoryBean, InitializingBean, DisposableBean, - PersistenceExceptionTranslator { +public class CassandraCqlSessionFactoryBean + implements FactoryBean, InitializingBean, DisposableBean, PersistenceExceptionTranslator { + + protected final Logger logger = LoggerFactory.getLogger(getClass()); + protected final PersistenceExceptionTranslator exceptionTranslator = new CassandraExceptionTranslator(); private Cluster cluster; private List startupScripts = Collections.emptyList(); + private List shutdownScripts = Collections.emptyList(); - protected final Logger logger = LoggerFactory.getLogger(getClass()); - - protected final PersistenceExceptionTranslator exceptionTranslator = new CassandraExceptionTranslator(); - private Session session; private String keyspaceName; - /* (non-Javadoc) */ + /* (non-Javadoc) + * @see org.springframework.beans.factory.FactoryBean#getObject() + */ @Override public Session getObject() { return this.session; } - /* (non-Javadoc) */ + /* (non-Javadoc) + * @see org.springframework.beans.factory.FactoryBean#getObjectType() + */ @Override public Class getObjectType() { return (this.session != null ? this.session.getClass() : Session.class); } - /* (non-Javadoc) */ + /* (non-Javadoc) + * @see org.springframework.beans.factory.FactoryBean#isSingleton() + */ @Override public boolean isSingleton() { return true; } - /* (non-Javadoc) */ + /* (non-Javadoc) + * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet() + */ @Override public void afterPropertiesSet() throws Exception { + this.session = connect(getKeyspaceName()); executeScripts(getStartupScripts()); } - /* (non-Javadoc) */ Session connect(String keyspaceName) { + return (StringUtils.hasText(keyspaceName) ? getCluster().connect(keyspaceName) : getCluster().connect()); } - /* (non-Javadoc) */ + /* (non-Javadoc) + * @see org.springframework.beans.factory.DisposableBean#destroy() + */ @Override public void destroy() throws Exception { + executeScripts(getShutdownScripts()); getSession().close(); } /** - * Executes the given Cassandra CQL scripts. The {@link Session} must be connected when this method is called. + * Executes the given Cassandra CQL scripts. The {@link Session} must be connected when this method is called. */ protected void executeScripts(List scripts) { + if (!CollectionUtils.isEmpty(scripts)) { + CqlOperations template = newCqlOperations(getSession()); - for (String script : scripts) { + scripts.forEach(script -> { logger.info("executing raw CQL [{}]", script); template.execute(script); - } + }); } } - /* (non-Javadoc) */ + /** + * @param session + * @return + */ CqlOperations newCqlOperations(Session session) { return new CqlTemplate(session); } - /* (non-Javadoc) */ + /* (non-Javadoc) + * @see org.springframework.dao.support.PersistenceExceptionTranslator#translateExceptionIfPossible(java.lang.RuntimeException) + */ @Override public DataAccessException translateExceptionIfPossible(RuntimeException e) { return this.exceptionTranslator.translateExceptionIfPossible(e); @@ -140,6 +158,7 @@ public class CassandraCqlSessionFactoryBean implements FactoryBean, Ini * @see #getObject() */ public boolean isConnected() { + Session session = getObject(); return !(session == null || session.isClosed()); } @@ -153,6 +172,7 @@ public class CassandraCqlSessionFactoryBean implements FactoryBean, Ini * @see #getCluster() */ public void setCluster(Cluster cluster) { + Assert.notNull(cluster, "Cluster must not be null"); this.cluster = cluster; } @@ -166,13 +186,14 @@ public class CassandraCqlSessionFactoryBean implements FactoryBean, Ini * @see #setCluster(Cluster) */ protected Cluster getCluster() { + Assert.state(this.cluster != null, "Cluster was not properly initialized"); return this.cluster; } /** - * Sets the name of the Cassandra Keyspace to connect to. Passing null, an empty String, - * or whitespace will cause the Cassandra System Keyspace to be used. + * Sets the name of the Cassandra Keyspace to connect to. Passing {@code null}, an empty String, or whitespace will + * cause the Cassandra System Keyspace to be used. * * @param keyspaceName a String indicating the name of the Keyspace in which to connect. * @see #getKeyspaceName() @@ -199,6 +220,7 @@ public class CassandraCqlSessionFactoryBean implements FactoryBean, Ini * @see com.datastax.driver.core.Session */ protected Session getSession() { + Session session = getObject(); Assert.state(session != null, "Session was not properly initialized"); return session; @@ -208,7 +230,7 @@ public class CassandraCqlSessionFactoryBean implements FactoryBean, Ini * Sets CQL scripts to be executed immediately after the session is connected. */ public void setStartupScripts(List scripts) { - this.startupScripts = (scripts != null ? new ArrayList(scripts) : Collections.emptyList()); + this.startupScripts = (scripts != null ? new ArrayList<>(scripts) : Collections.emptyList()); } /** @@ -222,7 +244,7 @@ public class CassandraCqlSessionFactoryBean implements FactoryBean, Ini * Sets CQL scripts to be executed immediately before the session is shutdown. */ public void setShutdownScripts(List scripts) { - this.shutdownScripts = (scripts != null ? new ArrayList(scripts) : Collections.emptyList()); + this.shutdownScripts = (scripts != null ? new ArrayList<>(scripts) : Collections.emptyList()); } /** diff --git a/spring-cql/src/main/java/org/springframework/cassandra/config/CassandraCqlTemplateFactoryBean.java b/spring-cql/src/main/java/org/springframework/cassandra/config/CassandraCqlTemplateFactoryBean.java index a46fb50cd..787339149 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/config/CassandraCqlTemplateFactoryBean.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/config/CassandraCqlTemplateFactoryBean.java @@ -1,12 +1,12 @@ /* - * Copyright 2013-2016 the original author or authors. - * + * Copyright 2013-2017 the original author or authors. + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. @@ -24,7 +24,7 @@ import com.datastax.driver.core.Session; /** * Factory for configuring a {@link CqlTemplate}. - * + * * @author Matthew T. Adams * @author Mark Paluch */ @@ -33,8 +33,7 @@ public class CassandraCqlTemplateFactoryBean implements FactoryBean private CqlTemplate template; private Session session; - /* - * (non-Javadoc) + /* (non-Javadoc) * @see org.springframework.beans.factory.FactoryBean#getObject() */ @Override @@ -42,8 +41,7 @@ public class CassandraCqlTemplateFactoryBean implements FactoryBean return template; } - /* - * (non-Javadoc) + /* (non-Javadoc) * @see org.springframework.beans.factory.FactoryBean#getObjectType() */ @Override @@ -51,8 +49,7 @@ public class CassandraCqlTemplateFactoryBean implements FactoryBean return CqlTemplate.class; } - /* - * (non-Javadoc) + /* (non-Javadoc) * @see org.springframework.beans.factory.FactoryBean#isSingleton() */ @Override @@ -60,8 +57,7 @@ public class CassandraCqlTemplateFactoryBean implements FactoryBean return true; } - /* - * (non-Javadoc) + /* (non-Javadoc) * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet() */ @Override @@ -76,7 +72,7 @@ public class CassandraCqlTemplateFactoryBean implements FactoryBean * Sets the Cassandra {@link Session} to use. The {@link CqlTemplate} will use the logged keyspace of the underlying * {@link Session}. Don't change the keyspace using CQL but use multiple {@link Session} and * {@link CqlTemplate} beans. - * + * * @param session must not be {@literal null}. */ public void setSession(Session session) { diff --git a/spring-cql/src/main/java/org/springframework/cassandra/config/DataCenterReplication.java b/spring-cql/src/main/java/org/springframework/cassandra/config/DataCenterReplication.java index d2d3cf4fc..dc2575953 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/config/DataCenterReplication.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/config/DataCenterReplication.java @@ -20,19 +20,48 @@ package org.springframework.cassandra.config; */ public class DataCenterReplication { - public static DataCenterReplication[] dcrs(DataCenterReplication... dcrs) { - return dcrs; - } - - public static DataCenterReplication dcr(String dataCenter, long replicationFactor) { + /** + * Creates a new {@link DataCenterReplication} given {@code dataCenter} and {@code replicationFactor}. + * + * @param dataCenter must not be {@literal null}. + * @param replicationFactor + * @return + */ + public static DataCenterReplication of(String dataCenter, long replicationFactor) { return new DataCenterReplication(dataCenter, replicationFactor); } - public String dataCenter; - public long replicationFactor; + private final String dataCenter; + private final long replicationFactor; + + private DataCenterReplication(String dataCenter, long replicationFactor) { - public DataCenterReplication(String dataCenter, long replicationFactor) { this.dataCenter = dataCenter; this.replicationFactor = replicationFactor; } + + /** + * @return the data center. + */ + public String getDataCenter() { + return dataCenter; + } + + /** + * @return the replication factor. + */ + public long getReplicationFactor() { + return replicationFactor; + } + + @Override + public String toString() { + + StringBuffer sb = new StringBuffer(); + sb.append(getClass().getSimpleName()); + sb.append(" [dataCenter='").append(dataCenter).append('\''); + sb.append(", replicationFactor=").append(replicationFactor); + sb.append(']'); + return sb.toString(); + } } diff --git a/spring-cql/src/main/java/org/springframework/cassandra/config/KeyspaceAction.java b/spring-cql/src/main/java/org/springframework/cassandra/config/KeyspaceAction.java index 8d06e23eb..394ac5f61 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/config/KeyspaceAction.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/config/KeyspaceAction.java @@ -1,12 +1,12 @@ /* - * Copyright 2013-2014 the original author or authors. - * + * Copyright 2013-2017 the original author or authors. + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. @@ -17,9 +17,9 @@ package org.springframework.cassandra.config; /** * Available actions for Keyspace Specifications - * + * * @author David Webb */ public enum KeyspaceAction { - CREATE, CREATE_DROP, ALTER; + CREATE, CREATE_DROP, ALTER } diff --git a/spring-cql/src/main/java/org/springframework/cassandra/config/KeyspaceActionSpecificationFactoryBean.java b/spring-cql/src/main/java/org/springframework/cassandra/config/KeyspaceActionSpecificationFactoryBean.java index 34bd5e027..33b3980c0 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/config/KeyspaceActionSpecificationFactoryBean.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/config/KeyspaceActionSpecificationFactoryBean.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2014 the original author or authors. + * Copyright 2013-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,17 +41,16 @@ import org.springframework.util.Assert; * * @author David Webb */ -public class KeyspaceActionSpecificationFactoryBean implements FactoryBean>>, - InitializingBean, DisposableBean { +public class KeyspaceActionSpecificationFactoryBean + implements FactoryBean>>, InitializingBean, DisposableBean { private KeyspaceAction action; private String name; - private List networkTopologyDataCenters = new LinkedList(); - - private List networkTopologyReplicationFactors = new LinkedList(); + private List networkTopologyDataCenters = new LinkedList<>(); + private List networkTopologyReplicationFactors = new LinkedList<>(); private ReplicationStrategy replicationStrategy; private long replicationFactor; @@ -60,11 +59,13 @@ public class KeyspaceActionSpecificationFactoryBean implements FactoryBean> specs = new HashSet>(); + private Set> specs = new HashSet<>(); + /* (non-Javadoc) + * @see org.springframework.beans.factory.DisposableBean#destroy() + */ @Override - public void destroy() throws Exception { - + public void destroy() { action = null; name = null; networkTopologyDataCenters = null; @@ -73,8 +74,11 @@ public class KeyspaceActionSpecificationFactoryBean implements FactoryBean replicationStrategyMap = new HashMap(); + Map replicationStrategyMap = new HashMap<>(); replicationStrategyMap.put(new DefaultOption("class", String.class, true, false, true), replicationStrategy.getValue()); @@ -135,16 +138,25 @@ public class KeyspaceActionSpecificationFactoryBean implements FactoryBean> getObject() throws Exception { return specs; } + /* (non-Javadoc) + * @see org.springframework.beans.factory.FactoryBean#getObjectType() + */ @Override public Class getObjectType() { return Set.class; } + /* (non-Javadoc) + * @see org.springframework.beans.factory.FactoryBean#isSingleton() + */ @Override public boolean isSingleton() { return false; diff --git a/spring-cql/src/main/java/org/springframework/cassandra/config/KeyspaceAttributes.java b/spring-cql/src/main/java/org/springframework/cassandra/config/KeyspaceAttributes.java index ff0bd35a5..a828bdd37 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/config/KeyspaceAttributes.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/config/KeyspaceAttributes.java @@ -1,12 +1,12 @@ /* - * Copyright 2013-2014 the original author or authors. - * + * Copyright 2013-2017 the original author or authors. + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. @@ -26,9 +26,10 @@ import org.springframework.cassandra.core.util.MapBuilder; /** * Keyspace attributes. - * + * * @author Alex Shvid * @author Matthew T. Adams + * @author Mark Paluch */ public class KeyspaceAttributes { @@ -68,7 +69,7 @@ public class KeyspaceAttributes { ReplicationStrategy.NETWORK_TOPOLOGY_STRATEGY.getValue()); for (DataCenterReplication dcr : dataCenterReplications) { - builder.entry(new DefaultOption(dcr.dataCenter, Long.class, true, false, false), dcr.replicationFactor); + builder.entry(new DefaultOption(dcr.getDataCenter(), Long.class, true, false, false), dcr.getReplicationFactor()); } return builder.build(); @@ -77,7 +78,7 @@ public class KeyspaceAttributes { private ReplicationStrategy replicationStrategy = DEFAULT_REPLICATION_STRATEGY; private long replicationFactor = DEFAULT_REPLICATION_FACTOR; private boolean durableWrites = DEFAULT_DURABLE_WRITES; - private Map replicasPerNodeByDataCenter = new HashMap(); + private Map replicasPerNodeByDataCenter = new HashMap<>(); public ReplicationStrategy getReplicationStrategy() { return replicationStrategy; diff --git a/spring-cql/src/main/java/org/springframework/cassandra/config/MultiLevelListFlattenerFactoryBean.java b/spring-cql/src/main/java/org/springframework/cassandra/config/MultiLevelListFlattenerFactoryBean.java index 49f0e4a88..504143c1a 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/config/MultiLevelListFlattenerFactoryBean.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/config/MultiLevelListFlattenerFactoryBean.java @@ -1,12 +1,12 @@ /* - * Copyright 2013-2014 the original author or authors. - * + * Copyright 2013-2017 the original author or authors. + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. @@ -15,14 +15,15 @@ */ package org.springframework.cassandra.config; -import java.util.ArrayList; +import java.util.Collection; import java.util.List; +import java.util.stream.Collectors; import org.springframework.beans.factory.FactoryBean; /** * Given List of Lists where all child Lists contain the same class, then a single level List of is generated. - * + * * @author David Webb * @param */ @@ -32,15 +33,7 @@ public class MultiLevelListFlattenerFactoryBean implements FactoryBean getObject() throws Exception { - List list = new ArrayList(); - - for (List topList : multiLevelList) { - for (T t : topList) { - list.add(t); - } - } - - return list; + return multiLevelList.stream().flatMap(Collection::stream).collect(Collectors.toList()); } @Override diff --git a/spring-cql/src/main/java/org/springframework/cassandra/config/MultiLevelSetFlattenerFactoryBean.java b/spring-cql/src/main/java/org/springframework/cassandra/config/MultiLevelSetFlattenerFactoryBean.java index a695deb1b..30acbc98c 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/config/MultiLevelSetFlattenerFactoryBean.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/config/MultiLevelSetFlattenerFactoryBean.java @@ -1,12 +1,12 @@ /* * Copyright 2013-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. * 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. @@ -15,6 +15,7 @@ */ package org.springframework.cassandra.config; +import java.util.Collection; import java.util.HashSet; import java.util.Set; @@ -24,9 +25,9 @@ import org.springframework.beans.factory.FactoryBean; /** * Given Set of Sets where all child Sets contain the same class, then a single level Set of is generated. - * + * * @author David Webb - * @param + * @param TODO: Remove me */ public class MultiLevelSetFlattenerFactoryBean implements FactoryBean> { @@ -36,15 +37,13 @@ public class MultiLevelSetFlattenerFactoryBean implements FactoryBean> @Override public Set getObject() throws Exception { - Set set = new HashSet(); + Set set = new HashSet<>(); - for (Set topSet : multiLevelSet) { - for (T t : topSet) { - log.debug(t.toString()); - log.debug("Set contains -> " + set.contains(t)); - set.add(t); - } - } + multiLevelSet.stream().flatMap(Collection::stream).forEach(t -> { + log.debug(t.toString()); + log.debug("Set contains -> " + set.contains(t)); + set.add(t); + }); return set; } diff --git a/spring-cql/src/main/java/org/springframework/cassandra/config/PoolingOptionsFactoryBean.java b/spring-cql/src/main/java/org/springframework/cassandra/config/PoolingOptionsFactoryBean.java index 9aea52fce..428a8fef7 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/config/PoolingOptionsFactoryBean.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/config/PoolingOptionsFactoryBean.java @@ -15,18 +15,18 @@ */ package org.springframework.cassandra.config; - -import static org.springframework.util.ReflectionUtils.invokeMethod; +import static org.springframework.util.ReflectionUtils.*; import java.lang.reflect.Method; +import java.util.Optional; import java.util.concurrent.Executor; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; +import org.springframework.util.ReflectionUtils; import com.datastax.driver.core.HostDistance; import com.datastax.driver.core.PoolingOptions; -import org.springframework.util.ReflectionUtils; /** * Spring {@link FactoryBean} for the Cassandra Java driver {@link PoolingOptions}. @@ -44,14 +44,16 @@ public class PoolingOptionsFactoryBean implements FactoryBean, I private static final PoolingOptions DEFAULT = new PoolingOptions(); - private static final Method SET_MAX_QUEUE_SIZE; - private static final Method GET_MAX_QUEUE_SIZE; + // Compatibility between 3.1.1 and earlier Cassandra driver versions + private static final Optional SET_MAX_QUEUE_SIZE; + + // Compatibility between 3.1.1 and earlier Cassandra driver versions + private static final Optional GET_MAX_QUEUE_SIZE; static { - SET_MAX_QUEUE_SIZE = ReflectionUtils - .findMethod(PoolingOptions.class, "setMaxQueueSize", int.class); - GET_MAX_QUEUE_SIZE = ReflectionUtils - .findMethod(PoolingOptions.class, "getMaxQueueSize"); + SET_MAX_QUEUE_SIZE = Optional + .ofNullable(ReflectionUtils.findMethod(PoolingOptions.class, "setMaxQueueSize", int.class)); + GET_MAX_QUEUE_SIZE = Optional.ofNullable(ReflectionUtils.findMethod(PoolingOptions.class, "getMaxQueueSize")); } private Executor initializationExecutor; @@ -83,7 +85,7 @@ public class PoolingOptionsFactoryBean implements FactoryBean, I public void afterPropertiesSet() throws Exception { poolingOptions = configureRemoteHostDistancePoolingOptions( - configureLocalHostDistancePoolingOptions(newPoolingOptions())); + configureLocalHostDistancePoolingOptions(newPoolingOptions())); if (heartbeatIntervalSeconds != DEFAULT.getHeartbeatIntervalSeconds()) { poolingOptions.setHeartbeatIntervalSeconds(heartbeatIntervalSeconds); @@ -101,22 +103,18 @@ public class PoolingOptionsFactoryBean implements FactoryBean, I poolingOptions.setPoolTimeoutMillis(poolTimeoutMilliseconds); } - if (!isDefaultMaxQueueSize() && SET_MAX_QUEUE_SIZE != null) { - invokeMethod(SET_MAX_QUEUE_SIZE, poolingOptions, maxQueueSize); + if (!isDefaultMaxQueueSize()) { + SET_MAX_QUEUE_SIZE.ifPresent(method -> invokeMethod(method, poolingOptions, maxQueueSize)); } } private boolean isDefaultMaxQueueSize() { - if(GET_MAX_QUEUE_SIZE != null){ + return GET_MAX_QUEUE_SIZE.map(method -> { - Integer defaultMaxQueueSize = (Integer) invokeMethod(GET_MAX_QUEUE_SIZE, poolingOptions); - if(defaultMaxQueueSize.intValue() == maxQueueSize){ - return true; - } - } - - return false; + Integer defaultMaxQueueSize = (Integer) invokeMethod(method, poolingOptions); + return defaultMaxQueueSize.intValue() == maxQueueSize; + }).orElse(false); } /* @@ -128,12 +126,11 @@ public class PoolingOptionsFactoryBean implements FactoryBean, I } /** - * Constructs and returns a {@link PoolingOptionsFactoryBean.HostDistancePoolingOptions} instance initialized - * with the {@link HostDistance#LOCAL}-based {@link PoolingOptions} as configured on this - * {@link PoolingOptionsFactoryBean}. + * Constructs and returns a {@link PoolingOptionsFactoryBean.HostDistancePoolingOptions} instance initialized with the + * {@link HostDistance#LOCAL}-based {@link PoolingOptions} as configured on this {@link PoolingOptionsFactoryBean}. * * @return {@link PoolingOptionsFactoryBean.HostDistancePoolingOptions} initialized with this - * {@link PoolingOptionsFactoryBean}'s {@link HostDistance#LOCAL}-based {@link PoolingOptions}. + * {@link PoolingOptionsFactoryBean}'s {@link HostDistance#LOCAL}-based {@link PoolingOptions}. * @see com.datastax.driver.core.HostDistance#LOCAL * @see com.datastax.driver.core.PoolingOptions * @see org.springframework.cassandra.config.PoolingOptionsFactoryBean.HostDistancePoolingOptions @@ -141,16 +138,15 @@ public class PoolingOptionsFactoryBean implements FactoryBean, I */ protected HostDistancePoolingOptions newLocalHostDistancePoolingOptions() { return LocalHostDistancePoolingOptions.create(getLocalCoreConnections(), getLocalMaxConnections(), - getLocalMaxSimultaneousRequests(), getLocalMinSimultaneousRequests()); + getLocalMaxSimultaneousRequests(), getLocalMinSimultaneousRequests()); } /** - * Constructs and returns a {@link PoolingOptionsFactoryBean.HostDistancePoolingOptions} instance initialized - * with the {@link HostDistance#REMOTE}-based {@link PoolingOptions} as configured on this - * {@link PoolingOptionsFactoryBean}. + * Constructs and returns a {@link PoolingOptionsFactoryBean.HostDistancePoolingOptions} instance initialized with the + * {@link HostDistance#REMOTE}-based {@link PoolingOptions} as configured on this {@link PoolingOptionsFactoryBean}. * * @return {@link PoolingOptionsFactoryBean.HostDistancePoolingOptions} initialized with this - * {@link PoolingOptionsFactoryBean}'s {@link HostDistance#REMOTE}-based {@link PoolingOptions}. + * {@link PoolingOptionsFactoryBean}'s {@link HostDistance#REMOTE}-based {@link PoolingOptions}. * @see com.datastax.driver.core.HostDistance#REMOTE * @see com.datastax.driver.core.PoolingOptions * @see org.springframework.cassandra.config.PoolingOptionsFactoryBean.HostDistancePoolingOptions @@ -158,7 +154,7 @@ public class PoolingOptionsFactoryBean implements FactoryBean, I */ protected HostDistancePoolingOptions newRemoteHostDistancePoolingOptions() { return RemoteHostDistancePoolingOptions.create(getRemoteCoreConnections(), getRemoteMaxConnections(), - getRemoteMaxSimultaneousRequests(), getRemoteMinSimultaneousRequests()); + getRemoteMaxSimultaneousRequests(), getRemoteMinSimultaneousRequests()); } /** @@ -359,8 +355,8 @@ public class PoolingOptionsFactoryBean implements FactoryBean, I } /** - * Sets the threshold that triggers the creation of a new connection to a host - * for the {@link HostDistance#LOCAL} scope. + * Sets the threshold that triggers the creation of a new connection to a host for the {@link HostDistance#LOCAL} + * scope. * * @param localMinSimultaneousRequests threshold triggering the creation of local connections to a host. */ @@ -369,8 +365,8 @@ public class PoolingOptionsFactoryBean implements FactoryBean, I } /** - * Gets the threshold that triggers the creation of a new connection to a host - * for the {@link HostDistance#LOCAL} scope. + * Gets the threshold that triggers the creation of a new connection to a host for the {@link HostDistance#LOCAL} + * scope. * * @return the {@code localMinSimultaneousRequests}. */ @@ -433,8 +429,8 @@ public class PoolingOptionsFactoryBean implements FactoryBean, I } /** - * Sets the threshold that triggers the creation of a new connection to a host - * for the {@link HostDistance#REMOTE} scope. + * Sets the threshold that triggers the creation of a new connection to a host for the {@link HostDistance#REMOTE} + * scope. * * @param remoteMinSimultaneousRequests threshold triggering the creation of remote connections to a host. */ @@ -443,8 +439,8 @@ public class PoolingOptionsFactoryBean implements FactoryBean, I } /** - * Gets the threshold that triggers the creation of a new connection to a host - * for the {@link HostDistance#REMOTE} scope. + * Gets the threshold that triggers the creation of a new connection to a host for the {@link HostDistance#REMOTE} + * scope. * * @return the {@code remoteMinSimultaneousRequests}. */ @@ -476,7 +472,7 @@ public class PoolingOptionsFactoryBean implements FactoryBean, I * @param newConnectionThreshold threshold that triggers the creation of a new connection to a host. */ protected HostDistancePoolingOptions(Integer coreConnectionsPerHost, Integer maxConnectionsPerHost, - Integer maxRequestsPerConnection, Integer newConnectionThreshold) { + Integer maxRequestsPerConnection, Integer newConnectionThreshold) { this.coreConnectionsPerHost = coreConnectionsPerHost; this.maxConnectionsPerHost = maxConnectionsPerHost; @@ -616,8 +612,8 @@ public class PoolingOptionsFactoryBean implements FactoryBean, I static class LocalHostDistancePoolingOptions extends HostDistancePoolingOptions { /** - * Creates an instance of {@link LocalHostDistancePoolingOptions} initialized with {@link PoolingOptions} - * based on {@link HostDistance#LOCAL}. + * Creates an instance of {@link LocalHostDistancePoolingOptions} initialized with {@link PoolingOptions} based on + * {@link HostDistance#LOCAL}. * * @param coreConnectionsPerHost core number of connections per host. * @param maxConnectionsPerHost maximum number of connections per host. @@ -628,12 +624,12 @@ public class PoolingOptionsFactoryBean implements FactoryBean, I Integer maxRequestsPerConnection, Integer newConnectionThreshold) { return new LocalHostDistancePoolingOptions(coreConnectionsPerHost, maxConnectionsPerHost, - maxRequestsPerConnection, newConnectionThreshold); + maxRequestsPerConnection, newConnectionThreshold); } /** - * Constructs an instance of {@link LocalHostDistancePoolingOptions} initialized with {@link PoolingOptions} - * based on {@link HostDistance#LOCAL}. + * Constructs an instance of {@link LocalHostDistancePoolingOptions} initialized with {@link PoolingOptions} based + * on {@link HostDistance#LOCAL}. * * @param coreConnectionsPerHost core number of connections per host. * @param maxConnectionsPerHost maximum number of connections per host. @@ -667,8 +663,8 @@ public class PoolingOptionsFactoryBean implements FactoryBean, I static class RemoteHostDistancePoolingOptions extends HostDistancePoolingOptions { /** - * Creates an instance of {@link RemoteHostDistancePoolingOptions} initialized with {@link PoolingOptions} - * based on {@link HostDistance#REMOTE}. + * Creates an instance of {@link RemoteHostDistancePoolingOptions} initialized with {@link PoolingOptions} based on + * {@link HostDistance#REMOTE}. * * @param coreConnectionsPerHost core number of connections per host. * @param maxConnectionsPerHost maximum number of connections per host. @@ -676,15 +672,15 @@ public class PoolingOptionsFactoryBean implements FactoryBean, I * @param newConnectionThreshold threshold that triggers the creation of a new connection to a host. */ static RemoteHostDistancePoolingOptions create(Integer coreConnectionsPerHost, Integer maxConnectionsPerHost, - Integer maxRequestsPerConnection, Integer newConnectionThreshold) { + Integer maxRequestsPerConnection, Integer newConnectionThreshold) { return new RemoteHostDistancePoolingOptions(coreConnectionsPerHost, maxConnectionsPerHost, - maxRequestsPerConnection, newConnectionThreshold); + maxRequestsPerConnection, newConnectionThreshold); } /** - * Constructs an instance of {@link RemoteHostDistancePoolingOptions} initialized with {@link PoolingOptions} - * based on {@link HostDistance#REMOTE}. + * Constructs an instance of {@link RemoteHostDistancePoolingOptions} initialized with {@link PoolingOptions} based + * on {@link HostDistance#REMOTE}. * * @param coreConnectionsPerHost core number of connections per host. * @param maxConnectionsPerHost maximum number of connections per host. @@ -692,7 +688,7 @@ public class PoolingOptionsFactoryBean implements FactoryBean, I * @param newConnectionThreshold threshold that triggers the creation of a new connection to a host. */ RemoteHostDistancePoolingOptions(Integer coreConnectionsPerHost, Integer maxConnectionsPerHost, - Integer maxRequestsPerConnection, Integer newConnectionThreshold) { + Integer maxRequestsPerConnection, Integer newConnectionThreshold) { super(coreConnectionsPerHost, maxConnectionsPerHost, maxRequestsPerConnection, newConnectionThreshold); } diff --git a/spring-cql/src/main/java/org/springframework/cassandra/config/SocketOptionsFactoryBean.java b/spring-cql/src/main/java/org/springframework/cassandra/config/SocketOptionsFactoryBean.java index 8733983f3..afa257f65 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/config/SocketOptionsFactoryBean.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/config/SocketOptionsFactoryBean.java @@ -38,20 +38,30 @@ public class SocketOptionsFactoryBean implements FactoryBean, Ini private Integer receiveBufferSize; private Integer sendBufferSize; - SocketOptions socketOptions; + private SocketOptions socketOptions; + /* (non-Javadoc) + * @see org.springframework.beans.factory.FactoryBean#getObject() + */ @Override public SocketOptions getObject() throws Exception { return socketOptions; } + /* (non-Javadoc) + * @see org.springframework.beans.factory.FactoryBean#getObjectType() + */ @Override public Class getObjectType() { return SocketOptions.class; } + /* (non-Javadoc) + * @see org.springframework.beans.factory.DisposableBean#destroy() + */ @Override public void destroy() throws Exception { + connectTimeoutMillis = null; keepAlive = null; readTimeoutMillis = null; @@ -62,6 +72,9 @@ public class SocketOptionsFactoryBean implements FactoryBean, Ini sendBufferSize = null; } + /* (non-Javadoc) + * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet() + */ @Override public void afterPropertiesSet() throws Exception { @@ -101,6 +114,9 @@ public class SocketOptionsFactoryBean implements FactoryBean, Ini } + /* (non-Javadoc) + * @see org.springframework.beans.factory.FactoryBean#isSingleton() + */ @Override public boolean isSingleton() { return true; diff --git a/spring-cql/src/main/java/org/springframework/cassandra/config/xml/CassandraCqlClusterParser.java b/spring-cql/src/main/java/org/springframework/cassandra/config/xml/CassandraCqlClusterParser.java index 4243f951f..444e9c691 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/config/xml/CassandraCqlClusterParser.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/config/xml/CassandraCqlClusterParser.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2016 the original author or authors. + * Copyright 2013-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -61,7 +61,7 @@ public class CassandraCqlClusterParser extends AbstractBeanDefinitionParser { String id = super.resolveId(element, definition, parserContext); - return (StringUtils.hasText(id) ? id : DefaultCqlBeanNames.CLUSTER); + return StringUtils.hasText(id) ? id : DefaultCqlBeanNames.CLUSTER; } /* (non-Javadoc) @@ -131,10 +131,10 @@ public class CassandraCqlClusterParser extends AbstractBeanDefinitionParser { */ protected void parseChildElements(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) { - ManagedSet keyspaceActionSpecificationBeanDefinitions = new ManagedSet(); + ManagedSet keyspaceActionSpecificationBeanDefinitions = new ManagedSet<>(); - List startupScripts = new ArrayList(); - List shutdownScripts = new ArrayList(); + List startupScripts = new ArrayList<>(); + List shutdownScripts = new ArrayList<>(); BeanDefinitionBuilder poolingOptionsBuilder = BeanDefinitionBuilder .genericBeanDefinition(PoolingOptionsFactoryBean.class); @@ -184,7 +184,7 @@ public class CassandraCqlClusterParser extends AbstractBeanDefinitionParser { * @param parserContext XML parser context and state. * @return the {@link BeanDefinition} or {@literal null} if action is not given. */ - BeanDefinition newKeyspaceActionSpecificationBeanDefinition(Element element, ParserContext parserContext) { + private BeanDefinition newKeyspaceActionSpecificationBeanDefinition(Element element, ParserContext parserContext) { BeanDefinitionBuilder builder = BeanDefinitionBuilder .genericBeanDefinition(KeyspaceActionSpecificationFactoryBean.class); @@ -210,10 +210,10 @@ public class CassandraCqlClusterParser extends AbstractBeanDefinitionParser { * @param element {@link Element} to parse. * @param builder The {@link BeanDefinitionBuilder} to add the replication to */ - void parseReplication(Element element, BeanDefinitionBuilder builder) { + private void parseReplication(Element element, BeanDefinitionBuilder builder) { - ManagedList networkTopologyDataCenters = new ManagedList(); - ManagedList networkTopologyReplicationFactors = new ManagedList(); + ManagedList networkTopologyDataCenters = new ManagedList<>(); + ManagedList networkTopologyReplicationFactors = new ManagedList<>(); if (element != null) { addOptionalPropertyValue(builder, "replicationStrategy", element, "class", @@ -241,12 +241,13 @@ public class CassandraCqlClusterParser extends AbstractBeanDefinitionParser { * @param keyspaceActionSpecificationBeanDefinitions The List of Definitions to flatten * @return A single level List of KeyspaceActionSpecifications */ - Object newKeyspaceSetFlattenerBeanDefinition(Element element, ParserContext parserContext, + private Object newKeyspaceSetFlattenerBeanDefinition(Element element, ParserContext parserContext, ManagedSet keyspaceActionSpecificationBeanDefinitions) { BeanDefinitionBuilder builder = BeanDefinitionBuilder .genericBeanDefinition(MultiLevelSetFlattenerFactoryBean.class); + // TODO: introduce a typed reference instead of Set of Sets. builder.addPropertyValue("multiLevelSet", keyspaceActionSpecificationBeanDefinitions); return getSourceBeanDefinition(builder, parserContext, element); diff --git a/spring-cql/src/main/java/org/springframework/cassandra/config/xml/DefaultCqlBeanNames.java b/spring-cql/src/main/java/org/springframework/cassandra/config/xml/DefaultCqlBeanNames.java index b63d5e82d..4ba2a6647 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/config/xml/DefaultCqlBeanNames.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/config/xml/DefaultCqlBeanNames.java @@ -1,12 +1,12 @@ /* * 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. diff --git a/spring-cql/src/main/java/org/springframework/cassandra/config/xml/ParsingUtils.java b/spring-cql/src/main/java/org/springframework/cassandra/config/xml/ParsingUtils.java index 6b038cd87..a340e94aa 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/config/xml/ParsingUtils.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/config/xml/ParsingUtils.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2016 the original author or authors. + * Copyright 2013-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,6 +28,7 @@ import org.w3c.dom.Element; * Utility class for parsing Cassandra XML namespace configuration meta-data. * * @author John Blum + * @author Mark Paluch * @see org.springframework.beans.factory.config.BeanDefinition * @see org.springframework.beans.factory.support.BeanDefinitionBuilder * @see org.springframework.beans.factory.xml.ParserContext @@ -209,26 +210,25 @@ public abstract class ParsingUtils { } /** - * Adds the named property and value, or reference to the given {@link BeanDefinitionBuilder} with an optional - * default value if the value has not been specified. + * Adds the named property and value, or reference to the given {@link BeanDefinitionBuilder} with an optional default + * value if the value has not been specified. *

- * If required is false, value is null or empty, - * and defaultValue is null or empty, then no property is added to the bean definition - * and this method silently returns. + * If {@code required} is false, value is null or empty, and {@code defaultValue} is null or + * empty, then no property is added to the bean definition and this method silently returns. * * @param builder {@link BeanDefinitionBuilder} used to build the {@link BeanDefinition}. * @param propertyName name of the property to add. * @param value value for the property being added. * @param defaultValue default value for the property if value is null or empty. - * @param required If true, then value must not be null or empty. If false, - * then value may be null and the defaultValue will be used. If required is - * false, value is null or empty, and defaultValue is null or empty, - * then no property is added to the bean definition and this method silently returns. - * @param reference If true, then the valuevalue for the named property is - * considered a reference to another bean in the Spring context. + * @param required If {@code true}, then value must not be null or empty. If false, then + * {@code value} may be null and the defaultValue will be used. If required is + * {@code false}, value is null or empty, and defaultValue is null or empty, then + * no property is added to the bean definition and this method silently returns. + * @param reference If {@code true}, then the valuevalue for the named property is considered a reference + * to another bean in the Spring context. * @return the given {@link BeanDefinitionBuilder}. - * @throws IllegalArgumentException if either the {@link BeanDefinitionBuilder} is null - * or the propertyName has not been specified. + * @throws IllegalArgumentException if either the {@link BeanDefinitionBuilder} is null or the {@code propertyName} + * has not been specified. * @see BeanDefinitionBuilder#addPropertyReference(String, String) * @see BeanDefinitionBuilder#addPropertyValue(String, Object) */ diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/ArgumentPreparedStatementBinder.java b/spring-cql/src/main/java/org/springframework/cassandra/core/ArgumentPreparedStatementBinder.java index e4dda65db..5b496da68 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/ArgumentPreparedStatementBinder.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/ArgumentPreparedStatementBinder.java @@ -38,6 +38,9 @@ public class ArgumentPreparedStatementBinder implements PreparedStatementBinder this.args = args; } + /* (non-Javadoc) + * @see org.springframework.cassandra.core.PreparedStatementBinder#bindValues(com.datastax.driver.core.PreparedStatement) + */ @Override public BoundStatement bindValues(PreparedStatement ps) throws DriverException { return args != null ? ps.bind(args) : ps.bind(); diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/AsyncCqlTemplate.java b/spring-cql/src/main/java/org/springframework/cassandra/core/AsyncCqlTemplate.java index b0a7863d2..68d6cf3bd 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/AsyncCqlTemplate.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/AsyncCqlTemplate.java @@ -80,7 +80,7 @@ import com.google.common.util.concurrent.Futures; public class AsyncCqlTemplate extends CassandraAccessor implements AsyncCqlOperations { /** - * Constructs a new, uninitialized {@link AsyncCqlTemplate}. Note: The {@link SessionFactory} has to be set before + * Create a new, uninitialized {@link AsyncCqlTemplate}. Note: The {@link SessionFactory} has to be set before * using the instance. * * @see #setSessionFactory(SessionFactory) @@ -88,7 +88,7 @@ public class AsyncCqlTemplate extends CassandraAccessor implements AsyncCqlOpera public AsyncCqlTemplate() {} /** - * Constructs a new {@link AsyncCqlTemplate} with the given {@link Session}. + * Create a new {@link AsyncCqlTemplate} with the given {@link Session}. * * @param session the active Cassandra {@link Session}, must not be {@literal null}. * @throws IllegalStateException if {@link Session} is {@literal null}. @@ -450,17 +450,15 @@ public class AsyncCqlTemplate extends CassandraAccessor implements AsyncCqlOpera logger.debug("Preparing statement [{}] using {}", toCql(preparedStatementCreator), preparedStatementCreator); } - Session currentSession = getCurrentSession(); - - return new ExceptionTranslatingListenableFutureAdapter<>(new MappingListenableFutureAdapter<>( - preparedStatementCreator.createPreparedStatement(currentSession), preparedStatement -> { - try { - return action.doInPreparedStatement(currentSession, - applyStatementSettings(preparedStatement)); - } catch (DriverException e) { - throw translateException("PreparedStatementCallback", preparedStatement.toString(), e); - } - }), getExceptionTranslator()); + Session currentSession = getCurrentSession();return new ExceptionTranslatingListenableFutureAdapter<>( + new MappingListenableFutureAdapter<>(preparedStatementCreator.createPreparedStatement(currentSession), + preparedStatement -> { + try { + return action.doInPreparedStatement(currentSession,applyStatementSettings(preparedStatement)); + } catch (DriverException e) { + throw translateException("PreparedStatementCallback", preparedStatement.toString(), e); + } + }), getExceptionTranslator()); } catch (DriverException e) { throw translateException("PreparedStatementCallback", toCql(preparedStatementCreator), e); @@ -588,8 +586,8 @@ public class AsyncCqlTemplate extends CassandraAccessor implements AsyncCqlOpera ListenableFuture results = query(preparedStatementCreator, preparedStatementBinder, newResultSetExtractor(rowCallbackHandler)); - return new ExceptionTranslatingListenableFutureAdapter<>( - new MappingListenableFutureAdapter<>(results, o -> null), getExceptionTranslator()); + return new ExceptionTranslatingListenableFutureAdapter<>(new MappingListenableFutureAdapter<>( + results, o -> null), getExceptionTranslator()); } /* @@ -625,8 +623,8 @@ public class AsyncCqlTemplate extends CassandraAccessor implements AsyncCqlOpera ListenableFuture results = query(newAsyncPreparedStatementCreator(cql), newPreparedStatementBinder(args), newResultSetExtractor(rowCallbackHandler)); - return new ExceptionTranslatingListenableFutureAdapter<>( - new MappingListenableFutureAdapter<>(results, o -> null), getExceptionTranslator()); + return new ExceptionTranslatingListenableFutureAdapter<>(new MappingListenableFutureAdapter<>( + results, o -> null), getExceptionTranslator()); } /* @@ -663,8 +661,8 @@ public class AsyncCqlTemplate extends CassandraAccessor implements AsyncCqlOpera ListenableFuture results = query(newAsyncPreparedStatementCreator(cql), preparedStatementBinder, newResultSetExtractor(rowCallbackHandler)); - return new ExceptionTranslatingListenableFutureAdapter<>( - new MappingListenableFutureAdapter<>(results, o -> null), getExceptionTranslator()); + return new ExceptionTranslatingListenableFutureAdapter<>(new MappingListenableFutureAdapter<>( + results, o -> null), getExceptionTranslator()); } /* @@ -733,8 +731,8 @@ public class AsyncCqlTemplate extends CassandraAccessor implements AsyncCqlOpera ListenableFuture> results = query(newAsyncPreparedStatementCreator(cql), newPreparedStatementBinder(args), newResultSetExtractor(rowMapper, 1)); - return new ExceptionTranslatingListenableFutureAdapter<>( - new MappingListenableFutureAdapter<>(results, DataAccessUtils::requiredSingleResult), getExceptionTranslator()); + return new ExceptionTranslatingListenableFutureAdapter<>(new MappingListenableFutureAdapter<>( + results, DataAccessUtils::requiredSingleResult), getExceptionTranslator()); } /* diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/AsynchronousQueryListener.java b/spring-cql/src/main/java/org/springframework/cassandra/core/AsynchronousQueryListener.java index ecbf904fa..82aa842d3 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/AsynchronousQueryListener.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/AsynchronousQueryListener.java @@ -1,12 +1,12 @@ /* - * Copyright 2013-2014 the original author or authors. - * + * Copyright 2013-2017 the original author or authors. + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. @@ -19,7 +19,7 @@ import com.datastax.driver.core.ResultSetFuture; /** * Interface used to give an implementation access to a {@link ResultSetFuture} after the query has completed. - * + * * @author David Webb * @author Matthew T. Adams */ @@ -27,8 +27,8 @@ public interface AsynchronousQueryListener { /** * Called upon query completion. - * + * * @param rsf The {@link ResultSetFuture}. Called when the query operation is completed. */ - public void onQueryComplete(ResultSetFuture rsf); + void onQueryComplete(ResultSetFuture rsf); } diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/CachedPreparedStatementCreator.java b/spring-cql/src/main/java/org/springframework/cassandra/core/CachedPreparedStatementCreator.java index 7a4df513e..a874ef62e 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/CachedPreparedStatementCreator.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/CachedPreparedStatementCreator.java @@ -1,12 +1,12 @@ /* - * Copyright 2013-2016 the original author or authors. - * + * Copyright 2013-2017 the original author or authors. + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. @@ -33,13 +33,13 @@ import com.datastax.driver.core.exceptions.DriverException; *

* {@link CachedPreparedStatementCreator} is thread-safe and does not require external synchronization when used by * concurrent threads. - * + * * @author David Webb * @author Mark Paluch */ public class CachedPreparedStatementCreator implements PreparedStatementCreator { - private static final Map> CACHE = new ConcurrentHashMap>(); + private static final Map> CACHE = new ConcurrentHashMap<>(); protected final Logger log = LoggerFactory.getLogger(getClass()); @@ -47,7 +47,7 @@ public class CachedPreparedStatementCreator implements PreparedStatementCreator /** * Create a {@link PreparedStatementCreator} from the provided CQL. - * + * * @param cql must not be empty or {@literal null}. */ public CachedPreparedStatementCreator(String cql) { diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/ColumnMapRowMapper.java b/spring-cql/src/main/java/org/springframework/cassandra/core/ColumnMapRowMapper.java index 64b9c7097..5e43d0f1c 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/ColumnMapRowMapper.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/ColumnMapRowMapper.java @@ -41,6 +41,9 @@ import com.datastax.driver.core.Row; */ public class ColumnMapRowMapper implements RowMapper> { + /* (non-Javadoc) + * @see org.springframework.cassandra.core.RowMapper#mapRow(com.datastax.driver.core.Row, int) + */ @Override public Map mapRow(Row rs, int rowNum) { @@ -62,7 +65,8 @@ public class ColumnMapRowMapper implements RowMapper> { *

* By default, a linked case-insensitive Map will be created. * - * @param columnCount the column count, to be used as initial capacity for the {@link Map}, must not be {@literal null}. + * @param columnCount the column count, to be used as initial capacity for the {@link Map}, must not be + * {@literal null}. * @return the new Map instance. * @see org.springframework.util.LinkedCaseInsensitiveMap */ diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/CqlTemplate.java b/spring-cql/src/main/java/org/springframework/cassandra/core/CqlTemplate.java index 00c3ad10b..f7225317a 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/CqlTemplate.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/CqlTemplate.java @@ -80,7 +80,7 @@ import com.datastax.driver.core.exceptions.DriverException; public class CqlTemplate extends CassandraAccessor implements CqlOperations { /** - * Constructs a new, uninitialized {@link CqlTemplate}. Note: The {@link SessionFactory} has to be set before using + * Create a new, uninitialized {@link CqlTemplate}. Note: The {@link SessionFactory} has to be set before using * the instance. * * @see #setSessionFactory(SessionFactory) @@ -88,7 +88,7 @@ public class CqlTemplate extends CassandraAccessor implements CqlOperations { public CqlTemplate() {} /** - * Constructs a new {@link CqlTemplate} initialized with the given {@link Session}. + * Create a new {@link CqlTemplate} initialized with the given {@link Session}. * * @param session the active Cassandra {@link Session}. * @throws IllegalStateException if {@link Session} is {@literal null}. diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/ExceptionTranslatingListenableFutureAdapter.java b/spring-cql/src/main/java/org/springframework/cassandra/core/ExceptionTranslatingListenableFutureAdapter.java index 480641407..5f72f633a 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/ExceptionTranslatingListenableFutureAdapter.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/ExceptionTranslatingListenableFutureAdapter.java @@ -97,8 +97,7 @@ class ExceptionTranslatingListenableFutureAdapter implements ListenableFuture future.addCallback(callback); } - /* - * (non-Javadoc) + /* (non-Javadoc) * @see org.springframework.util.concurrent.ListenableFuture#addCallback(org.springframework.util.concurrent.SuccessCallback, org.springframework.util.concurrent.FailureCallback) */ @Override @@ -106,8 +105,7 @@ class ExceptionTranslatingListenableFutureAdapter implements ListenableFuture future.addCallback(successCallback, failureCallback); } - /* - * (non-Javadoc) + /* (non-Javadoc) * @see java.util.concurrent.Future#cancel(boolean) */ @Override @@ -115,8 +113,7 @@ class ExceptionTranslatingListenableFutureAdapter implements ListenableFuture return adaptee.cancel(mayInterruptIfRunning); } - /* - * (non-Javadoc) + /* (non-Javadoc) * @see java.util.concurrent.Future#isCancelled() */ @Override @@ -124,8 +121,7 @@ class ExceptionTranslatingListenableFutureAdapter implements ListenableFuture return adaptee.isCancelled(); } - /* - * (non-Javadoc) + /* (non-Javadoc) * @see java.util.concurrent.Future#isDone() */ @Override @@ -133,8 +129,7 @@ class ExceptionTranslatingListenableFutureAdapter implements ListenableFuture return future.isDone(); } - /* - * (non-Javadoc) + /* (non-Javadoc) * @see java.util.concurrent.Future#get() */ @Override @@ -142,8 +137,7 @@ class ExceptionTranslatingListenableFutureAdapter implements ListenableFuture return future.get(); } - /* - * (non-Javadoc) + /* (non-Javadoc) * @see java.util.concurrent.Future#get(long, java.util.concurrent.TimeUnit) */ @Override diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/GuavaListenableFutureAdapter.java b/spring-cql/src/main/java/org/springframework/cassandra/core/GuavaListenableFutureAdapter.java index 79b37b7d2..e9b43c56d 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/GuavaListenableFutureAdapter.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/GuavaListenableFutureAdapter.java @@ -91,8 +91,7 @@ public class GuavaListenableFutureAdapter implements ListenableFuture { return settableFuture; } - /* - * (non-Javadoc) + /* (non-Javadoc) * @see org.springframework.util.concurrent.ListenableFuture#addCallback(org.springframework.util.concurrent.ListenableFutureCallback) */ @Override @@ -100,8 +99,7 @@ public class GuavaListenableFutureAdapter implements ListenableFuture { future.addCallback(callback); } - /* - * (non-Javadoc) + /* (non-Javadoc) * @see org.springframework.util.concurrent.ListenableFuture#addCallback(org.springframework.util.concurrent.SuccessCallback, org.springframework.util.concurrent.FailureCallback) */ @Override @@ -109,8 +107,7 @@ public class GuavaListenableFutureAdapter implements ListenableFuture { future.addCallback(successCallback, failureCallback); } - /* - * (non-Javadoc) + /* (non-Javadoc) * @see java.util.concurrent.Future#cancel(boolean) */ @Override @@ -118,8 +115,7 @@ public class GuavaListenableFutureAdapter implements ListenableFuture { return adaptee.cancel(mayInterruptIfRunning); } - /* - * (non-Javadoc) + /* (non-Javadoc) * @see java.util.concurrent.Future#isCancelled() */ @Override @@ -127,8 +123,7 @@ public class GuavaListenableFutureAdapter implements ListenableFuture { return adaptee.isCancelled(); } - /* - * (non-Javadoc) + /* (non-Javadoc) * @see java.util.concurrent.Future#isDone() */ @Override @@ -136,8 +131,7 @@ public class GuavaListenableFutureAdapter implements ListenableFuture { return future.isDone(); } - /* - * (non-Javadoc) + /* (non-Javadoc) * @see java.util.concurrent.Future#get() */ @Override @@ -145,8 +139,7 @@ public class GuavaListenableFutureAdapter implements ListenableFuture { return future.get(); } - /* - * (non-Javadoc) + /* (non-Javadoc) * @see java.util.concurrent.Future#get(long, java.util.concurrent.TimeUnit) */ @Override diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/Ordering.java b/spring-cql/src/main/java/org/springframework/cassandra/core/Ordering.java index 8422ea355..273287e97 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/Ordering.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/Ordering.java @@ -1,12 +1,12 @@ /* - * Copyright 2013-2014 the original author or authors. - * + * Copyright 2013-2017 the original author or authors. + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. @@ -20,7 +20,7 @@ import java.util.Comparator; /** * Enum for Cassandra primary key column ordering. Implements {@link Comparator} in that {@link Ordering#ASCENDING} is * ordered before {@link Ordering#DESCENDING}. - * + * * @author Matthew T. Adams */ public enum Ordering implements Comparator { @@ -37,7 +37,7 @@ public enum Ordering implements Comparator { private String cql; - private Ordering(String cql) { + Ordering(String cql) { this.cql = cql; } @@ -53,10 +53,10 @@ public enum Ordering implements Comparator { if (l == r) { return 0; } - if (l == null && r != null) { + if (l == null) { return 1; } - if (l != null && r == null) { + if (r == null) { return -1; } return (l == ASCENDING && r == DESCENDING) ? 1 : -1; diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/PreparedStatementBinder.java b/spring-cql/src/main/java/org/springframework/cassandra/core/PreparedStatementBinder.java index 8548c1e06..61cf92c1f 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/PreparedStatementBinder.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/PreparedStatementBinder.java @@ -1,12 +1,12 @@ /* - * Copyright 2013-2014 the original author or authors. - * + * Copyright 2013-2017 the original author or authors. + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. @@ -35,14 +35,15 @@ import com.datastax.driver.core.exceptions.DriverException; * @author David Webb * @author Mark Paluch * @see CqlTemplate#query(String, PreparedStatementBinder, ResultSetExtractor) + * @see AsyncCqlTemplate#query(AsyncPreparedStatementCreator, PreparedStatementBinder, ResultSetExtractor) * @see ReactiveCqlTemplate#query(String, PreparedStatementBinder, ReactiveResultSetExtractor) */ public interface PreparedStatementBinder { /** * Bind parameter values on the given {@link PreparedStatement}. - * - * @param ps the PreparedStatement to invoke setter methods on + * + * @param ps the PreparedStatement to invoke setter methods on. * @throws DriverException if a {@link DriverException} is encountered (i.e. there is no need to catch * {@link DriverException}) */ diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/PreparedStatementCallback.java b/spring-cql/src/main/java/org/springframework/cassandra/core/PreparedStatementCallback.java index 4d72c8039..e54cdc5a5 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/PreparedStatementCallback.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/PreparedStatementCallback.java @@ -34,6 +34,8 @@ import com.datastax.driver.core.exceptions.DriverException; * * @author David Webb * @author Mark Paluch + * @see AsyncCqlTemplate#execute(String, PreparedStatementCallback) + * @see AsyncCqlTemplate#execute(PreparedStatementCreator, PreparedStatementCallback) * @see CqlTemplate#execute(String, PreparedStatementCallback) * @see CqlTemplate#execute(PreparedStatementCreator, PreparedStatementCallback) */ @@ -54,10 +56,11 @@ public interface PreparedStatementCallback { * @return a result object publisher. * @throws DriverException if thrown by a session method, to be auto-converted to a DataAccessException. * @throws DataAccessException in case of custom exceptions. + * @see AsyncCqlTemplate#queryForObject(String, Class, Object...) + * @see AsyncCqlTemplate#queryForList(String, Class, Object...) * @see CqlTemplate#queryForObject(String, Class, Object...) * @see CqlTemplate#queryForList(String, Object...) */ T doInPreparedStatement(Session session, PreparedStatement preparedStatement) throws DriverException, DataAccessException; - } diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/PreparedStatementCreator.java b/spring-cql/src/main/java/org/springframework/cassandra/core/PreparedStatementCreator.java index 4d37361d7..08c15dc52 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/PreparedStatementCreator.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/PreparedStatementCreator.java @@ -43,5 +43,4 @@ public interface PreparedStatementCreator { * of this method. The {@link CqlTemplate} class will handle them. */ PreparedStatement createPreparedStatement(Session session) throws DriverException; - } diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/PrimaryKeyType.java b/spring-cql/src/main/java/org/springframework/cassandra/core/PrimaryKeyType.java index 8174bea11..c3b374fc6 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/PrimaryKeyType.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/PrimaryKeyType.java @@ -41,10 +41,10 @@ public enum PrimaryKeyType implements Comparator { if (l == r) { return 0; } - if (l == null && r != null) { + if (l == null) { return 1; } - if (l != null && r == null) { + if (r == null) { return -1; } return l == PARTITIONED && r == CLUSTERED ? 1 : -1; diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/QueryForListListener.java b/spring-cql/src/main/java/org/springframework/cassandra/core/QueryForListListener.java index b787b7ca4..11e88154f 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/QueryForListListener.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/QueryForListListener.java @@ -1,3 +1,18 @@ +/* + * 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.cassandra.core; import java.util.List; @@ -5,8 +20,8 @@ import java.util.List; import com.datastax.driver.core.ResultSet; /** - * Listener used to receive asynchronous results expected as a List<T>. - * + * Listener used to receive asynchronous results expected as a {@code List}. + * * @author Matthew T. Adams * @param */ diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/QueryForListOfMapListener.java b/spring-cql/src/main/java/org/springframework/cassandra/core/QueryForListOfMapListener.java index 783625a7b..242fcbef2 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/QueryForListOfMapListener.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/QueryForListOfMapListener.java @@ -1,10 +1,25 @@ +/* + * 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.cassandra.core; import java.util.Map; /** - * Listener used to receive asynchronous results expected as a List<T>. - * + * Listener used to receive asynchronous results expected as a {@code List}. + * * @author Matthew T. Adams */ public interface QueryForListOfMapListener extends QueryForListListener> {} diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/QueryForMapListener.java b/spring-cql/src/main/java/org/springframework/cassandra/core/QueryForMapListener.java index 6b75ee0e4..953997b28 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/QueryForMapListener.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/QueryForMapListener.java @@ -1,3 +1,18 @@ +/* + * 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.cassandra.core; import java.util.Map; @@ -5,8 +20,8 @@ import java.util.Map; import com.datastax.driver.core.ResultSet; /** - * Listener used to receive asynchronous results expected as a List<Map<String,Object>>. - * + * Listener used to receive asynchronous results expected as a {@code List>}. + * * @author Matthew T. Adams * @param */ diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/QueryForObjectListener.java b/spring-cql/src/main/java/org/springframework/cassandra/core/QueryForObjectListener.java index b1b9ab021..f1f4da2d4 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/QueryForObjectListener.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/QueryForObjectListener.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2016-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,8 +18,8 @@ package org.springframework.cassandra.core; import com.datastax.driver.core.ResultSet; /** - * Listener used to receive asynchronous results expected as an object of type T or an {@link Exception}. - * + * Listener used to receive asynchronous results expected as an object of type {@code T} or an {@link Exception}. + * * @author Matthew T. Adams * @author Mark Paluch * @param @@ -28,14 +28,14 @@ public interface QueryForObjectListener { /** * Called upon query completion. - * + * * @param result the result, can be {@literal null} for empty single-record results. */ void onQueryComplete(T result); /** * Called if an exception is raised while getting or converting the {@link ResultSet}. - * + * * @param ex the exception that triggered the failure, never {@link null}. */ void onException(Exception ex); diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/ReactiveCqlTemplate.java b/spring-cql/src/main/java/org/springframework/cassandra/core/ReactiveCqlTemplate.java index d191ec267..b807cafc9 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/ReactiveCqlTemplate.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/ReactiveCqlTemplate.java @@ -15,7 +15,11 @@ */ package org.springframework.cassandra.core; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + import java.util.Map; +import java.util.Optional; import java.util.function.Function; import org.reactivestreams.Publisher; @@ -257,7 +261,8 @@ public class ReactiveCqlTemplate extends ReactiveCassandraAccessor implements Re @Override public Mono queryForObject(String cql, RowMapper rowMapper) throws DataAccessException { return query(cql, rowMapper).buffer(2).flatMap(list -> - Mono.just(DataAccessUtils.requiredSingleResult(list))).next(); + Mono.just(DataAccessUtils.requiredSingleResult(list))) + .next(); } /* (non-Javadoc) @@ -378,7 +383,8 @@ public class ReactiveCqlTemplate extends ReactiveCassandraAccessor implements Re @Override public Mono queryForObject(Statement statement, RowMapper rowMapper) throws DataAccessException { return query(statement, rowMapper).buffer(2).flatMap(list -> - Mono.just(DataAccessUtils.requiredSingleResult(list))).next(); + Mono.just(DataAccessUtils.requiredSingleResult(list))) + .next(); } /* (non-Javadoc) @@ -568,7 +574,8 @@ public class ReactiveCqlTemplate extends ReactiveCassandraAccessor implements Re @Override public Mono queryForObject(String cql, RowMapper rowMapper, Object... args) throws DataAccessException { return query(cql, rowMapper, args).buffer(2).flatMap(list -> - Mono.just(DataAccessUtils.requiredSingleResult(list))).next(); + Mono.just(DataAccessUtils.requiredSingleResult(list))) + .next(); } /* (non-Javadoc) @@ -638,7 +645,8 @@ public class ReactiveCqlTemplate extends ReactiveCassandraAccessor implements Re @Override public Mono execute(String cql, PreparedStatementBinder psb) throws DataAccessException { return query(new SimpleReactivePreparedStatementCreator(cql), psb, resultSet -> - Mono.just(resultSet.wasApplied())).next(); + Mono.just(resultSet.wasApplied())) + .next(); } /* (non-Javadoc) @@ -748,7 +756,8 @@ public class ReactiveCqlTemplate extends ReactiveCassandraAccessor implements Re */ protected Function> translateException(String task, String cql) { - return throwable -> Mono.error( + return throwable -> Mono + .error( throwable instanceof DriverException ? translate(task, cql, (DriverException) throwable) : throwable); } @@ -852,7 +861,11 @@ public class ReactiveCqlTemplate extends ReactiveCassandraAccessor implements Re */ private static String getCql(Object cqlProvider) { - return (cqlProvider instanceof CqlProvider ? ((CqlProvider) cqlProvider).getCql() : null); + return Optional.ofNullable(cqlProvider) // + .filter(o -> o instanceof CqlProvider) // + .map(o -> (CqlProvider) o) // + .map(CqlProvider::getCql) // + .orElse(null); } private class SimpleReactivePreparedStatementCreator implements ReactivePreparedStatementCreator, CqlProvider { diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/ResultSetExtractor.java b/spring-cql/src/main/java/org/springframework/cassandra/core/ResultSetExtractor.java index c5652ccc5..58a66095b 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/ResultSetExtractor.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/ResultSetExtractor.java @@ -15,11 +15,11 @@ */ package org.springframework.cassandra.core; +import org.springframework.dao.DataAccessException; + import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.exceptions.DriverException; -import org.springframework.dao.DataAccessException; - /** * Callback interface used by {@link CqlTemplate}'s query methods. Implementations of this interface perform the actual * work of extracting results from a {@link ResultSet}, but don't need to worry about exception handling. @@ -35,6 +35,7 @@ import org.springframework.dao.DataAccessException; * @author Matthew T. Adams * @author Mark Paluch * @since April 24, 2003 + * @see AsyncCqlTemplate * @see CqlTemplate * @see RowCallbackHandler * @see RowMapper diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/ResultSetFutureCancellable.java b/spring-cql/src/main/java/org/springframework/cassandra/core/ResultSetFutureCancellable.java deleted file mode 100644 index f204a9e3c..000000000 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/ResultSetFutureCancellable.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright 2013-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. - * 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.cassandra.core; - -import com.datastax.driver.core.ResultSetFuture; - -/** - * Convenient default implementation of a {@link Cancellable}. - * - * @author Matthew T. Adams - */ -public class ResultSetFutureCancellable implements Cancellable { - - ResultSetFuture rsf; - - public ResultSetFutureCancellable(ResultSetFuture rsf) { - this.rsf = rsf; - } - - @Override - public void cancel() { - rsf.cancel(true); - } -} diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/ResultSetFutureExtractor.java b/spring-cql/src/main/java/org/springframework/cassandra/core/ResultSetFutureExtractor.java index 16330308f..dd1523f6b 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/ResultSetFutureExtractor.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/ResultSetFutureExtractor.java @@ -1,12 +1,12 @@ /* * Copyright 2013-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. * 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. @@ -20,6 +20,10 @@ import org.springframework.dao.DataAccessException; import com.datastax.driver.core.ResultSetFuture; import com.datastax.driver.core.exceptions.DriverException; +/** + * @param + * @deprecated as of 2.0, not used anymore. + */ public interface ResultSetFutureExtractor { T extractData(ResultSetFuture rs) throws DriverException, DataAccessException; diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/RingMember.java b/spring-cql/src/main/java/org/springframework/cassandra/core/RingMember.java index 5fcc736b9..4bbba6ce8 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/RingMember.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/RingMember.java @@ -17,10 +17,15 @@ package org.springframework.cassandra.core; import java.io.Serializable; +import org.springframework.util.Assert; + import com.datastax.driver.core.Host; /** + * Domain object representing a Cassandra host. + * * @author David Webb + * @author Mark Paluch */ public final class RingMember implements Serializable { @@ -29,16 +34,47 @@ public final class RingMember implements Serializable { /* * Ring attributes */ - public String hostName; - public String address; - public String DC; - public String rack; + private final String hostName; - public RingMember(Host h) { - this.hostName = h.getAddress().getHostName(); - this.address = h.getAddress().getHostAddress(); - this.DC = h.getDatacenter(); - this.rack = h.getRack(); + private final String address; + + private final String dc; + + private final String rack; + + /** + * Creates a new {@link RingMember} given {@link Host}. + * + * @param host + * @return + */ + public static RingMember from(Host host) { + return new RingMember(host); } + private RingMember(Host host) { + + Assert.notNull(host, "Host must not be null"); + + this.hostName = host.getAddress().getHostName(); + this.address = host.getAddress().getHostAddress(); + this.dc = host.getDatacenter(); + this.rack = host.getRack(); + } + + public String getHostName() { + return hostName; + } + + public String getAddress() { + return address; + } + + public String getDataCenter() { + return dc; + } + + public String getRack() { + return rack; + } } diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/RingMemberHostMapper.java b/spring-cql/src/main/java/org/springframework/cassandra/core/RingMemberHostMapper.java index f377a4ae2..6da6d728d 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/RingMemberHostMapper.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/RingMemberHostMapper.java @@ -19,11 +19,11 @@ import java.util.Collection; import java.util.stream.Collectors; import java.util.stream.StreamSupport; +import org.springframework.util.Assert; + import com.datastax.driver.core.Host; import com.datastax.driver.core.exceptions.DriverException; -import org.springframework.util.Assert; - /** * {@link HostMapper} to to map hosts into {@link RingMember} objects. * @@ -43,6 +43,6 @@ public enum RingMemberHostMapper implements HostMapper { Assert.notNull(hosts, "Hosts must not be null"); - return StreamSupport.stream(hosts.spliterator(), false).map(RingMember::new).collect(Collectors.toList()); + return StreamSupport.stream(hosts.spliterator(), false).map(RingMember::from).collect(Collectors.toList()); } } diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/RowCallback.java b/spring-cql/src/main/java/org/springframework/cassandra/core/RowCallback.java index 377f87262..8a5426fac 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/RowCallback.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/RowCallback.java @@ -1,12 +1,12 @@ /* * Copyright 2013-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. * 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. @@ -19,11 +19,18 @@ import com.datastax.driver.core.Row; /** * Simple internal callback to allow operations on a {@link Row}. - * + * * @author Alex Shvid + * @deprecated as of 2.0. Superseded by {@link RowCallbackHandler}. */ - public interface RowCallback { + /** + * Implementations must implement this method to process each row of data in the + * {@link com.datastax.driver.core.ResultSet}. This method is only supposed to extract values of the current row. + * + * @param object + * @return + */ T doWith(Row object); } diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/RowCallbackHandler.java b/spring-cql/src/main/java/org/springframework/cassandra/core/RowCallbackHandler.java index 7c0950ff5..3f852ab25 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/RowCallbackHandler.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/RowCallbackHandler.java @@ -50,5 +50,4 @@ public interface RowCallbackHandler { * to catch {@link DriverException}) */ void processRow(Row row) throws DriverException; - } diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/RowIterator.java b/spring-cql/src/main/java/org/springframework/cassandra/core/RowIterator.java index cac4f1afb..c05b64eae 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/RowIterator.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/RowIterator.java @@ -1,12 +1,12 @@ /* * Copyright 2013-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. * 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. @@ -17,7 +17,9 @@ package org.springframework.cassandra.core; /** * @author David Webb + * @deprecated as of 2.0. This class is not used anymore. */ +@Deprecated public interface RowIterator { Object[] next(); diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/RowMapper.java b/spring-cql/src/main/java/org/springframework/cassandra/core/RowMapper.java index 706573018..511b09761 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/RowMapper.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/RowMapper.java @@ -46,5 +46,4 @@ public interface RowMapper { * to catch {@link DriverException}) */ T mapRow(Row row, int rowNum) throws DriverException; - } diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/SessionCallback.java b/spring-cql/src/main/java/org/springframework/cassandra/core/SessionCallback.java index 2e2b1c4cf..ec8a6f89f 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/SessionCallback.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/SessionCallback.java @@ -1,12 +1,12 @@ /* * Copyright 2013-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. * 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. @@ -43,7 +43,7 @@ public interface SessionCallback { * objects. Note that there's special support for single step actions: see {@link CqlTemplate#queryForObject} etc. A * thrown {@link RuntimeException} is treated as application exception: it gets propagated to the caller of the * template. - * + * * @param session active Cassandra Session, must not be {@literal null}. * @return a result object, or {@code null} if none. * @throws DriverException if thrown by a Session method, to be auto-converted to a {@link DataAccessException}. @@ -52,5 +52,4 @@ public interface SessionCallback { * @see CqlTemplate#queryForResultSet(String) */ T doInSession(Session session) throws DriverException, DataAccessException; - } diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/SimplePreparedStatementCreator.java b/spring-cql/src/main/java/org/springframework/cassandra/core/SimplePreparedStatementCreator.java index 9880d6b2a..6711e08eb 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/SimplePreparedStatementCreator.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/SimplePreparedStatementCreator.java @@ -1,12 +1,12 @@ /* - * Copyright 2013-2014 the original author or authors. - * + * Copyright 2013-2017 the original author or authors. + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. @@ -22,34 +22,43 @@ import com.datastax.driver.core.Session; import com.datastax.driver.core.exceptions.DriverException; /** - * This Prepared Statement Creator simply prepares a statement from the CQL string. This should not be used in - * Production systems with high volume reads and writes. Use {@link CachedPreparedStatementCreator} When preparing - * statements with Cassandra, each Statement should be prepared once and only once due to the overhead of preparing the - * statement. - * + * Trivial implementation of {@link PreparedStatementCreator}. This prepared statement creator simply prepares a + * statement from the CQL string. + *

+ * This implementation is useful for testing. It should not be used in production systems with high volume reads and + * writes. Use {@link CachedPreparedStatementCreator} When preparing statements with Cassandra, each Statement should be + * prepared once and only once due to the overhead of preparing the statement. + * * @author David Webb + * @author Mark Paluch */ -public class SimplePreparedStatementCreator implements PreparedStatementCreator { +public class SimplePreparedStatementCreator implements PreparedStatementCreator, CqlProvider { private final String cql; /** - * Create a PreparedStatementCreator from the provided CQL. - * - * @param cql + * Create a {@link SimplePreparedStatementCreator} given {@code cql}. + * + * @param cql must not be {@literal null}. */ public SimplePreparedStatementCreator(String cql) { + Assert.notNull(cql, "CQL is required to create a PreparedStatement"); this.cql = cql; } + /* (non-Javadoc) + * @see org.springframework.cassandra.core.CqlProvider#getCql() + */ public String getCql() { return this.cql; } + /* (non-Javadoc) + * @see org.springframework.cassandra.core.PreparedStatementCreator#createPreparedStatement(com.datastax.driver.core.Session) + */ @Override public PreparedStatement createPreparedStatement(Session session) throws DriverException { return session.prepare(this.cql); } - } diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/SingleColumnRowMapper.java b/spring-cql/src/main/java/org/springframework/cassandra/core/SingleColumnRowMapper.java index 587d1aa8c..abfd1082a 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/SingleColumnRowMapper.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/SingleColumnRowMapper.java @@ -34,6 +34,10 @@ import com.datastax.driver.core.exceptions.DriverException; * * @author Mark Paluch * @since 2.0 + * @see AsyncCqlTemplate#queryForList(String, Class) + * @see AsyncCqlTemplate#queryForObject(String, Class) + * @see CqlTemplate#queryForList(String, Class) + * @see CqlTemplate#queryForObject(String, Class) * @see ReactiveCqlTemplate#queryForFlux(String, Class) * @see ReactiveCqlTemplate#queryForObject(String, Class) */ diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/converter/AbstractResultSetConverter.java b/spring-cql/src/main/java/org/springframework/cassandra/core/converter/AbstractResultSetConverter.java index bf6d2ea70..0efc7f047 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/converter/AbstractResultSetConverter.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/converter/AbstractResultSetConverter.java @@ -1,3 +1,18 @@ +/* + * 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.cassandra.core.converter; import java.util.List; @@ -22,7 +37,7 @@ import com.datastax.driver.core.ResultSet; *

* If the converter throws due to the inability to convert a given {@link ResultSet}, it will throw an * {@link IllegalArgumentException}. - * + * * @author Matthew T. Adams * @param */ diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/converter/AbstractResultSetToBasicFixedTypeConverter.java b/spring-cql/src/main/java/org/springframework/cassandra/core/converter/AbstractResultSetToBasicFixedTypeConverter.java index 6cdfb3cf5..581dae755 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/converter/AbstractResultSetToBasicFixedTypeConverter.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/converter/AbstractResultSetToBasicFixedTypeConverter.java @@ -1,3 +1,18 @@ +/* + * 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.cassandra.core.converter; import org.springframework.core.convert.ConversionService; @@ -5,7 +20,7 @@ import org.springframework.core.convert.support.DefaultConversionService; /** * Thin wrapper that allows subclasses to delegate conversion of the given value to a {@link DefaultConversionService}. - * + * * @author Matthew T. Adams * @param */ diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/converter/ResultSetToArrayConverter.java b/spring-cql/src/main/java/org/springframework/cassandra/core/converter/ResultSetToArrayConverter.java index 62b0d9df7..d25442bf7 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/converter/ResultSetToArrayConverter.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/converter/ResultSetToArrayConverter.java @@ -70,7 +70,7 @@ public class ResultSetToArrayConverter implements Converter return null; } - List list = new ArrayList(); + List list = new ArrayList<>(); for (Row row : resultSet) { list.add(rowConverter.convert(row)); } diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/converter/ResultSetToBigDecimalConverter.java b/spring-cql/src/main/java/org/springframework/cassandra/core/converter/ResultSetToBigDecimalConverter.java index be32ecb2a..b9605f98e 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/converter/ResultSetToBigDecimalConverter.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/converter/ResultSetToBigDecimalConverter.java @@ -1,14 +1,35 @@ +/* + * 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.cassandra.core.converter; import java.math.BigDecimal; public class ResultSetToBigDecimalConverter extends AbstractResultSetToBasicFixedTypeConverter { + /* (non-Javadoc) + * @see org.springframework.cassandra.core.converter.AbstractResultSetConverter#doConvertSingleValue(java.lang.Object) + */ @Override protected BigDecimal doConvertSingleValue(Object object) { return CONVERTER.convert(object, BigDecimal.class); } + /* (non-Javadoc) + * @see org.springframework.cassandra.core.converter.AbstractResultSetConverter#getType() + */ @Override protected Class getType() { return BigDecimal.class; diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/converter/ResultSetToBigIntegerConverter.java b/spring-cql/src/main/java/org/springframework/cassandra/core/converter/ResultSetToBigIntegerConverter.java index acfee7288..09b9ee68a 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/converter/ResultSetToBigIntegerConverter.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/converter/ResultSetToBigIntegerConverter.java @@ -1,14 +1,35 @@ +/* + * 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.cassandra.core.converter; import java.math.BigInteger; public class ResultSetToBigIntegerConverter extends AbstractResultSetToBasicFixedTypeConverter { + /* (non-Javadoc) + * @see org.springframework.cassandra.core.converter.AbstractResultSetConverter#doConvertSingleValue(java.lang.Object) + */ @Override protected BigInteger doConvertSingleValue(Object object) { return CONVERTER.convert(object, BigInteger.class); } + /* (non-Javadoc) + * @see org.springframework.cassandra.core.converter.AbstractResultSetConverter#getType() + */ @Override protected Class getType() { return BigInteger.class; diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/converter/ResultSetToBooleanConverter.java b/spring-cql/src/main/java/org/springframework/cassandra/core/converter/ResultSetToBooleanConverter.java index bac02da22..9da0ca42d 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/converter/ResultSetToBooleanConverter.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/converter/ResultSetToBooleanConverter.java @@ -1,12 +1,33 @@ +/* + * 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.cassandra.core.converter; public class ResultSetToBooleanConverter extends AbstractResultSetToBasicFixedTypeConverter { + /* (non-Javadoc) + * @see org.springframework.cassandra.core.converter.AbstractResultSetConverter#doConvertSingleValue(java.lang.Object) + */ @Override protected Boolean doConvertSingleValue(Object object) { return CONVERTER.convert(object, Boolean.class); } + /* (non-Javadoc) + * @see org.springframework.cassandra.core.converter.AbstractResultSetConverter#getType() + */ @Override protected Class getType() { return Boolean.class; diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/converter/ResultSetToByteBufferConverter.java b/spring-cql/src/main/java/org/springframework/cassandra/core/converter/ResultSetToByteBufferConverter.java index 859dd3689..fa37f656a 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/converter/ResultSetToByteBufferConverter.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/converter/ResultSetToByteBufferConverter.java @@ -1,9 +1,27 @@ +/* + * 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.cassandra.core.converter; import java.nio.ByteBuffer; public class ResultSetToByteBufferConverter extends AbstractResultSetConverter { + /* (non-Javadoc) + * @see org.springframework.cassandra.core.converter.AbstractResultSetConverter#doConvertSingleValue(java.lang.Object) + */ @Override protected ByteBuffer doConvertSingleValue(Object object) { @@ -14,6 +32,9 @@ public class ResultSetToByteBufferConverter extends AbstractResultSetConverter getType() { return ByteBuffer.class; diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/converter/ResultSetToDateConverter.java b/spring-cql/src/main/java/org/springframework/cassandra/core/converter/ResultSetToDateConverter.java index 8737754ae..1f6c6efec 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/converter/ResultSetToDateConverter.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/converter/ResultSetToDateConverter.java @@ -1,14 +1,35 @@ +/* + * 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.cassandra.core.converter; import java.util.Date; public class ResultSetToDateConverter extends AbstractResultSetToBasicFixedTypeConverter { + /* (non-Javadoc) + * @see org.springframework.cassandra.core.converter.AbstractResultSetConverter#doConvertSingleValue(java.lang.Object) + */ @Override protected Date doConvertSingleValue(Object object) { return CONVERTER.convert(object, Date.class); } + /* (non-Javadoc) + * @see org.springframework.cassandra.core.converter.AbstractResultSetConverter#getType() + */ @Override protected Class getType() { return Date.class; diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/converter/ResultSetToDoubleConverter.java b/spring-cql/src/main/java/org/springframework/cassandra/core/converter/ResultSetToDoubleConverter.java index dda7fae99..d882d565d 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/converter/ResultSetToDoubleConverter.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/converter/ResultSetToDoubleConverter.java @@ -1,12 +1,33 @@ +/* + * 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.cassandra.core.converter; public class ResultSetToDoubleConverter extends AbstractResultSetToBasicFixedTypeConverter { + /* (non-Javadoc) + * @see org.springframework.cassandra.core.converter.AbstractResultSetConverter#doConvertSingleValue(java.lang.Object) + */ @Override protected Double doConvertSingleValue(Object object) { return CONVERTER.convert(object, Double.class); } + /* (non-Javadoc) + * @see org.springframework.cassandra.core.converter.AbstractResultSetConverter#getType() + */ @Override protected Class getType() { return Double.class; diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/converter/ResultSetToFloatConverter.java b/spring-cql/src/main/java/org/springframework/cassandra/core/converter/ResultSetToFloatConverter.java index a457bb685..4071a9cda 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/converter/ResultSetToFloatConverter.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/converter/ResultSetToFloatConverter.java @@ -1,12 +1,33 @@ +/* + * 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.cassandra.core.converter; public class ResultSetToFloatConverter extends AbstractResultSetToBasicFixedTypeConverter { + /* (non-Javadoc) + * @see org.springframework.cassandra.core.converter.AbstractResultSetConverter#doConvertSingleValue(java.lang.Object) + */ @Override protected Float doConvertSingleValue(Object object) { return CONVERTER.convert(object, Float.class); } + /* (non-Javadoc) + * @see org.springframework.cassandra.core.converter.AbstractResultSetConverter#getType() + */ @Override protected Class getType() { return Float.class; diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/converter/ResultSetToInetAddressConverter.java b/spring-cql/src/main/java/org/springframework/cassandra/core/converter/ResultSetToInetAddressConverter.java index 8a339273c..0c9899f32 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/converter/ResultSetToInetAddressConverter.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/converter/ResultSetToInetAddressConverter.java @@ -1,14 +1,35 @@ +/* + * 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.cassandra.core.converter; import java.net.InetAddress; public class ResultSetToInetAddressConverter extends AbstractResultSetToBasicFixedTypeConverter { + /* (non-Javadoc) + * @see org.springframework.cassandra.core.converter.AbstractResultSetConverter#doConvertSingleValue(java.lang.Object) + */ @Override protected InetAddress doConvertSingleValue(Object object) { return CONVERTER.convert(object, InetAddress.class); } + /* (non-Javadoc) + * @see org.springframework.cassandra.core.converter.AbstractResultSetConverter#getType() + */ @Override protected Class getType() { return InetAddress.class; diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/converter/ResultSetToIntegerConverter.java b/spring-cql/src/main/java/org/springframework/cassandra/core/converter/ResultSetToIntegerConverter.java index 5d9bbe273..80aaf4cac 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/converter/ResultSetToIntegerConverter.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/converter/ResultSetToIntegerConverter.java @@ -1,12 +1,33 @@ +/* + * 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.cassandra.core.converter; public class ResultSetToIntegerConverter extends AbstractResultSetToBasicFixedTypeConverter { + /* (non-Javadoc) + * @see org.springframework.cassandra.core.converter.AbstractResultSetConverter#doConvertSingleValue(java.lang.Object) + */ @Override protected Integer doConvertSingleValue(Object object) { return CONVERTER.convert(object, Integer.class); } + /* (non-Javadoc) + * @see org.springframework.cassandra.core.converter.AbstractResultSetConverter#getType() + */ @Override protected Class getType() { return Integer.class; diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/converter/ResultSetToListConverter.java b/spring-cql/src/main/java/org/springframework/cassandra/core/converter/ResultSetToListConverter.java index b963a29a2..2e2c3bf1d 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/converter/ResultSetToListConverter.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/converter/ResultSetToListConverter.java @@ -79,7 +79,7 @@ public class ResultSetToListConverter implements Converter> list = new ArrayList>(); + List> list = new ArrayList<>(); for (Row row : resultSet) { list.add(rowConverter.convert(row)); } diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/converter/ResultSetToListOfStringConverter.java b/spring-cql/src/main/java/org/springframework/cassandra/core/converter/ResultSetToListOfStringConverter.java index 09b3e19bb..f3053b4d1 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/converter/ResultSetToListOfStringConverter.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/converter/ResultSetToListOfStringConverter.java @@ -1,44 +1,54 @@ +/* + * 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.cassandra.core.converter; import java.util.ArrayList; import java.util.List; import java.util.Map; +import java.util.stream.Collectors; import org.springframework.util.StringUtils; public class ResultSetToListOfStringConverter extends AbstractResultSetConverter> { + /* (non-Javadoc) + * @see org.springframework.cassandra.core.converter.AbstractResultSetConverter#doConvertSingleValue(java.lang.Object) + */ @Override protected List doConvertSingleValue(Object object) { - List list = new ArrayList(); + List list = new ArrayList<>(); list.add(object == null ? null : object.toString()); return list; } + /* (non-Javadoc) + * @see org.springframework.cassandra.core.converter.AbstractResultSetConverter#doConvertSingleRow(java.util.Map) + */ @Override protected List doConvertSingleRow(Map row) { - - List list = new ArrayList(row.size()); - - for (Object value : row.values()) { - list.add(value == null ? null : value.toString()); - } - - return list; + return row.values().stream().map(value -> value == null ? null : value.toString()).collect(Collectors.toList()); } @Override protected List doConvertResultSet(List> resultSet) { - - List list = new ArrayList(resultSet.size()); - - for (Map row : resultSet) { - list.add(StringUtils.arrayToCommaDelimitedString(doConvertSingleRow(row).toArray())); - } - - return list; + return resultSet.stream().map(row -> doConvertSingleRow(row).toArray()) // + .map(StringUtils::arrayToCommaDelimitedString) // + .collect(Collectors.toList()); } @Override diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/converter/ResultSetToLongConverter.java b/spring-cql/src/main/java/org/springframework/cassandra/core/converter/ResultSetToLongConverter.java index 43ceba9d8..5a30788b6 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/converter/ResultSetToLongConverter.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/converter/ResultSetToLongConverter.java @@ -1,12 +1,33 @@ +/* + * 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.cassandra.core.converter; public class ResultSetToLongConverter extends AbstractResultSetToBasicFixedTypeConverter { + /* (non-Javadoc) + * @see org.springframework.cassandra.core.converter.AbstractResultSetConverter#doConvertSingleValue(java.lang.Object) + */ @Override protected Long doConvertSingleValue(Object object) { return CONVERTER.convert(object, Long.class); } + /* (non-Javadoc) + * @see org.springframework.cassandra.core.converter.AbstractResultSetConverter#getType() + */ @Override protected Class getType() { return Long.class; diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/converter/ResultSetToStringConverter.java b/spring-cql/src/main/java/org/springframework/cassandra/core/converter/ResultSetToStringConverter.java index c4e0e4fc7..e78dce62e 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/converter/ResultSetToStringConverter.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/converter/ResultSetToStringConverter.java @@ -1,3 +1,18 @@ +/* + * 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.cassandra.core.converter; import java.util.List; @@ -5,11 +20,17 @@ import java.util.Map; public class ResultSetToStringConverter extends AbstractResultSetConverter { + /* (non-Javadoc) + * @see org.springframework.cassandra.core.converter.AbstractResultSetConverter#doConvertSingleValue(java.lang.Object) + */ @Override protected String doConvertSingleValue(Object object) { return object == null ? null : object.toString(); } + /* (non-Javadoc) + * @see org.springframework.cassandra.core.converter.AbstractResultSetConverter#doConvertSingleRow(java.util.Map) + */ @Override protected String doConvertSingleRow(Map row) { diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/converter/ResultSetToUuidConverter.java b/spring-cql/src/main/java/org/springframework/cassandra/core/converter/ResultSetToUuidConverter.java index 4d7889413..dd0cef495 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/converter/ResultSetToUuidConverter.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/converter/ResultSetToUuidConverter.java @@ -1,14 +1,35 @@ +/* + * 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.cassandra.core.converter; import java.util.UUID; public class ResultSetToUuidConverter extends AbstractResultSetToBasicFixedTypeConverter { + /* (non-Javadoc) + * @see org.springframework.cassandra.core.converter.AbstractResultSetConverter#doConvertSingleValue(java.lang.Object) + */ @Override protected UUID doConvertSingleValue(Object object) { return CONVERTER.convert(object, UUID.class); } + /* (non-Javadoc) + * @see org.springframework.cassandra.core.converter.AbstractResultSetConverter#getType() + */ @Override protected Class getType() { return UUID.class; diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/converter/RowToArrayConverter.java b/spring-cql/src/main/java/org/springframework/cassandra/core/converter/RowToArrayConverter.java index aa6618e36..ba4685ca5 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/converter/RowToArrayConverter.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/converter/RowToArrayConverter.java @@ -1,3 +1,18 @@ +/* + * 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.cassandra.core.converter; import java.util.List; @@ -10,6 +25,9 @@ public class RowToArrayConverter implements Converter { protected RowToListConverter delegate = new RowToListConverter(); + /* (non-Javadoc) + * @see org.springframework.core.convert.converter.Converter#convert(java.lang.Object) + */ @Override public Object[] convert(Row row) { diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/converter/RowToListConverter.java b/spring-cql/src/main/java/org/springframework/cassandra/core/converter/RowToListConverter.java index 957aee2ea..8141b4036 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/converter/RowToListConverter.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/converter/RowToListConverter.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * 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. @@ -17,6 +17,7 @@ package org.springframework.cassandra.core.converter; import java.util.ArrayList; import java.util.List; +import java.util.stream.Collectors; import org.springframework.core.convert.converter.Converter; import org.springframework.data.convert.ReadingConverter; @@ -38,6 +39,9 @@ public class RowToListConverter implements Converter> { public final static RowToListConverter INSTANCE = new RowToListConverter(); + /* (non-Javadoc) + * @see org.springframework.core.convert.converter.Converter#convert(java.lang.Object) + */ @Override public List convert(Row row) { @@ -46,14 +50,8 @@ public class RowToListConverter implements Converter> { } ColumnDefinitions cols = row.getColumnDefinitions(); - List list = new ArrayList(cols.size()); - - for (Definition def : cols.asList()) { - String name = def.getName(); - - list.add(row.isNull(name) ? null : row.getObject(name)); - } - - return list; + return cols.asList().stream() // + .map(Definition::getName).map(name -> row.isNull(name) ? null : row.getObject(name)) // + .collect(Collectors.toList()); } } diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/converter/RowToMapConverter.java b/spring-cql/src/main/java/org/springframework/cassandra/core/converter/RowToMapConverter.java index b1b5ea327..b8ed7e24e 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/converter/RowToMapConverter.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/converter/RowToMapConverter.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * 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. @@ -38,6 +38,9 @@ public class RowToMapConverter implements Converter> { public final static RowToMapConverter INSTANCE = new RowToMapConverter(); + /* (non-Javadoc) + * @see org.springframework.core.convert.converter.Converter#convert(java.lang.Object) + */ @Override public Map convert(Row row) { @@ -46,14 +49,10 @@ public class RowToMapConverter implements Converter> { } ColumnDefinitions cols = row.getColumnDefinitions(); - Map map = new HashMap(cols.size()); + Map map = new HashMap<>(cols.size()); - for (Definition def : cols.asList()) { - - String name = def.getName(); - - map.put(name, row.isNull(name) ? null : row.getObject(name)); - } + cols.asList().stream().map(Definition::getName) + .forEach(name -> map.put(name, row.isNull(name) ? null : row.getObject(name))); return map; } diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/cql/CqlConstantType.java b/spring-cql/src/main/java/org/springframework/cassandra/core/cql/CqlConstantType.java index ff252ba9d..d870fff32 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/cql/CqlConstantType.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/cql/CqlConstantType.java @@ -1,3 +1,18 @@ +/* + * 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.cassandra.core.cql; import static org.springframework.cassandra.core.cql.CqlConstantType.Regex.*; @@ -14,7 +29,7 @@ public enum CqlConstantType { private Pattern pattern; - private CqlConstantType(Pattern pattern) { + CqlConstantType(Pattern pattern) { this.pattern = pattern; } diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/cql/CqlIdentifier.java b/spring-cql/src/main/java/org/springframework/cassandra/core/cql/CqlIdentifier.java index 62d252698..2327eecbd 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/cql/CqlIdentifier.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/cql/CqlIdentifier.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2016-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -69,10 +69,10 @@ public final class CqlIdentifier implements Comparable, Serializa /** * Create a new CQL identifier, optionally force-quoting it. Force-quoting can be used to preserve identifier case. *
    - *
  • If the given identifier is a legal quoted identifier or forceQuote is true, - * {@link #isQuoted()} will return true and the identifier will be quoted when rendered.
  • - *
  • If the given identifier is a legal unquoted identifier, {@link #isQuoted()} will return false, - * plus the name will be converted to lower case and rendered as such.
  • + *
  • If the given identifier is a legal quoted identifier or {@code forceQuote} is true, + * {@link #isQuoted()} will return {@code true} and the identifier will be quoted when rendered.
  • + *
  • If the given identifier is a legal unquoted identifier, {@link #isQuoted()} will return {@code false}, plus the + * name will be converted to lower case and rendered as such.
  • *
  • If the given identifier is illegal, an {@link IllegalArgumentException} is thrown.
  • *
* @@ -111,14 +111,14 @@ public final class CqlIdentifier implements Comparable, Serializa } /** - * Returns true if the given {@link CharSequence} is a legal unquoted identifier. + * Returns {@code true} if the given {@link CharSequence} is a legal unquoted identifier. */ public static boolean isUnquotedIdentifier(CharSequence chars) { return UNQUOTED.matcher(chars).matches() && !ReservedKeyword.isReserved(chars); } /** - * Returns true if the given {@link CharSequence} is a legal unquoted identifier. + * Returns {@code true} if the given {@link CharSequence} is a legal unquoted identifier. */ public static boolean isQuotedIdentifier(CharSequence chars) { return QUOTED.matcher(chars).matches() || ReservedKeyword.isReserved(chars); @@ -149,7 +149,7 @@ public final class CqlIdentifier implements Comparable, Serializa /** * Returns the identifier without encasing quotes, regardless of the value of {@link #isQuoted()}. For - * example, if {@link #isQuoted()} is true, then this value will be the same as {@link #toCql()} and + * example, if {@link #isQuoted()} is {@code true}, then this value will be the same as {@link #toCql()} and * {@link #toString()}. *

* This is needed, for example, to get the correct {@link TableMetadata} from @@ -168,8 +168,7 @@ public final class CqlIdentifier implements Comparable, Serializa /** * Appends the rendering of this identifier to the given {@link StringBuilder}, then returns that - * {@link StringBuilder}. If null is given, a new {@link StringBuilder} is created, appended to, and - * returned. + * {@link StringBuilder}. If {@code null} is given, a new {@link StringBuilder} is created, appended to, and returned. */ public StringBuilder toCql(StringBuilder builder) { return (builder != null ? builder : new StringBuilder()).append(toCql()); diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/cql/CqlStringUtils.java b/spring-cql/src/main/java/org/springframework/cassandra/core/cql/CqlStringUtils.java index 59670fce3..cfe203823 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/cql/CqlStringUtils.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/cql/CqlStringUtils.java @@ -1,12 +1,12 @@ /* * Copyright 2013-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. * 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. @@ -33,7 +33,7 @@ public class CqlStringUtils { /** * Renders the given string as a legal Cassandra string column or table option value, by escaping single quotes and - * encasing the result in single quotes. Given null, returns null. + * encasing the result in single quotes. Given {@code null}, returns null. */ public static String valuize(String candidate) { @@ -44,34 +44,32 @@ public class CqlStringUtils { } /** - * Doubles single quote characters (' -> ''). Given null, returns null. + * Doubles single quote characters (' -> ''). Given {@code null}, returns null. */ public static String escapeSingle(Object thing) { - return thing == null ? (String) null : thing.toString().replace(SINGLE_QUOTE, DOUBLE_SINGLE_QUOTE); + return thing == null ? null : thing.toString().replace(SINGLE_QUOTE, DOUBLE_SINGLE_QUOTE); } /** - * Doubles double quote characters (" -> ""). Given null, returns null. + * Doubles double quote characters (" -> ""). Given {@code null}, returns null. */ public static String escapeDouble(Object thing) { - return thing == null ? (String) null : thing.toString().replace(DOUBLE_QUOTE, DOUBLE_DOUBLE_QUOTE); + return thing == null ? null : thing.toString().replace(DOUBLE_QUOTE, DOUBLE_DOUBLE_QUOTE); } /** - * Surrounds given object's {@link Object#toString()} with single quotes. Given null, returns - * null. + * Surrounds given object's {@link Object#toString()} with single quotes. Given {@code null}, returns {@code null}. */ public static String singleQuote(Object thing) { - return thing == null ? (String) null : new StringBuilder().append(SINGLE_QUOTE).append(thing).append(SINGLE_QUOTE) + return thing == null ? null : new StringBuilder().append(SINGLE_QUOTE).append(thing).append(SINGLE_QUOTE) .toString(); } /** - * Surrounds given object's {@link Object#toString()} with double quotes. Given null, returns - * null. + * Surrounds given object's {@link Object#toString()} with double quotes. Given {@code null}, returns {@code null}. */ public static String doubleQuote(Object thing) { - return thing == null ? (String) null : new StringBuilder().append(DOUBLE_QUOTE).append(thing).append(DOUBLE_QUOTE) + return thing == null ? null : new StringBuilder().append(DOUBLE_QUOTE).append(thing).append(DOUBLE_QUOTE) .toString(); } @@ -79,12 +77,12 @@ public class CqlStringUtils { * Removed single quotes from quoted String option values */ public static String removeSingleQuotes(Object thing) { - return thing == null ? (String) null : ((String) thing).replaceAll(SINGLE_QUOTE, EMPTY_STRING); + return thing == null ? null : ((String) thing).replaceAll(SINGLE_QUOTE, EMPTY_STRING); } /** * Renders the given {@link DataType} as a CQL string. - * + * * @param dataType The {@link DataType} to render; must not be null. */ public static String toCql(DataType dataType) { diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/cql/KeyspaceIdentifier.java b/spring-cql/src/main/java/org/springframework/cassandra/core/cql/KeyspaceIdentifier.java index 47eb9b7d5..fb26205e1 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/cql/KeyspaceIdentifier.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/cql/KeyspaceIdentifier.java @@ -45,7 +45,7 @@ public final class KeyspaceIdentifier implements Comparable } /** - * Returns true if the given {@link CharSequence} is a legal keyspace identifier. + * Returns {@code true} if the given {@link CharSequence} is a legal keyspace identifier. */ public static boolean isIdentifier(CharSequence chars) { return PATTERN.matcher(chars).matches() && !ReservedKeyword.isReserved(chars); @@ -86,8 +86,7 @@ public final class KeyspaceIdentifier implements Comparable /** * Appends the rendering of this identifier to the given {@link StringBuilder}, then returns that - * {@link StringBuilder}. If null is given, a new {@link StringBuilder} is created, appended to, and - * returned. + * {@link StringBuilder}. If {@code null} is given, a new {@link StringBuilder} is created, appended to, and returned. */ public StringBuilder toCql(StringBuilder sb) { sb = sb == null ? new StringBuilder() : sb; diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/cql/generator/AlterColumnCqlGenerator.java b/spring-cql/src/main/java/org/springframework/cassandra/core/cql/generator/AlterColumnCqlGenerator.java index efaedaaaf..441a68974 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/cql/generator/AlterColumnCqlGenerator.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/cql/generator/AlterColumnCqlGenerator.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2014 the original author or authors. + * Copyright 2013-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,12 +15,12 @@ */ package org.springframework.cassandra.core.cql.generator; -import static org.springframework.cassandra.core.cql.CqlStringUtils.noNull; +import static org.springframework.cassandra.core.cql.CqlStringUtils.*; import org.springframework.cassandra.core.keyspace.AlterColumnSpecification; /** - * CQL generator for generating an ALTER column clause of an ALTER TABLE statement. + * CQL generator for generating an {@code ALTER} column clause of an ALTER TABLE statement. * * @author Matthew T. Adams * @see AlterColumnSpecification diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/cql/generator/AlterKeyspaceCqlGenerator.java b/spring-cql/src/main/java/org/springframework/cassandra/core/cql/generator/AlterKeyspaceCqlGenerator.java index 0f8eb4d59..7562c079b 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/cql/generator/AlterKeyspaceCqlGenerator.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/cql/generator/AlterKeyspaceCqlGenerator.java @@ -1,12 +1,12 @@ /* - * Copyright 2013-2014 the original author or authors. - * + * Copyright 2013-2017 the original author or authors. + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. @@ -15,7 +15,7 @@ */ package org.springframework.cassandra.core.cql.generator; -import static org.springframework.cassandra.core.cql.CqlStringUtils.noNull; +import static org.springframework.cassandra.core.cql.CqlStringUtils.*; import java.util.Map; @@ -23,8 +23,8 @@ import org.springframework.cassandra.core.keyspace.AlterKeyspaceSpecification; import org.springframework.cassandra.core.keyspace.Option; /** - * CQL generator for generating ALTER TABLE statements. - * + * CQL generator for generating {@code ALTER TABLE} statements. + * * @author Matthew T. Adams */ public class AlterKeyspaceCqlGenerator extends KeyspaceOptionsCqlGenerator { diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/cql/generator/CreateIndexCqlGenerator.java b/spring-cql/src/main/java/org/springframework/cassandra/core/cql/generator/CreateIndexCqlGenerator.java index a151d4c4b..b918862f7 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/cql/generator/CreateIndexCqlGenerator.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/cql/generator/CreateIndexCqlGenerator.java @@ -1,12 +1,12 @@ /* - * Copyright 2013-2014 the original author or authors. - * + * Copyright 2013-2017 the original author or authors. + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. @@ -15,14 +15,13 @@ */ package org.springframework.cassandra.core.cql.generator; -import static org.springframework.cassandra.core.cql.CqlStringUtils.noNull; +import static org.springframework.cassandra.core.cql.CqlStringUtils.*; import org.springframework.cassandra.core.keyspace.CreateIndexSpecification; -import org.springframework.util.StringUtils; /** - * CQL generator for generating a CREATE INDEX statement. - * + * CQL generator for generating a {@code CREATE INDEX} statement. + * * @author Matthew T. Adams * @author David Webb */ diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/cql/generator/CreateKeyspaceCqlGenerator.java b/spring-cql/src/main/java/org/springframework/cassandra/core/cql/generator/CreateKeyspaceCqlGenerator.java index 666a9827a..091dc3967 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/cql/generator/CreateKeyspaceCqlGenerator.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/cql/generator/CreateKeyspaceCqlGenerator.java @@ -1,12 +1,12 @@ /* - * Copyright 2013-2014 the original author or authors. - * + * Copyright 2013-2017 the original author or authors. + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. @@ -15,7 +15,7 @@ */ package org.springframework.cassandra.core.cql.generator; -import static org.springframework.cassandra.core.cql.CqlStringUtils.noNull; +import static org.springframework.cassandra.core.cql.CqlStringUtils.*; import java.util.Map; @@ -25,8 +25,8 @@ import org.springframework.cassandra.core.keyspace.KeyspaceOption; import org.springframework.cassandra.core.keyspace.Option; /** - * CQL generator for generating a CREATE TABLE statement. - * + * CQL generator for generating a {@code CREATE TABLE} statement. + * * @author Matthew T. Adams * @author Alex Shvid */ diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/cql/generator/CreateTableCqlGenerator.java b/spring-cql/src/main/java/org/springframework/cassandra/core/cql/generator/CreateTableCqlGenerator.java index cec361562..1172cbae4 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/cql/generator/CreateTableCqlGenerator.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/cql/generator/CreateTableCqlGenerator.java @@ -1,12 +1,12 @@ /* - * Copyright 2013-2014 the original author or authors. - * + * Copyright 2013-2017 the original author or authors. + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. @@ -15,9 +15,8 @@ */ package org.springframework.cassandra.core.cql.generator; -import static org.springframework.cassandra.core.cql.CqlStringUtils.noNull; -import static org.springframework.cassandra.core.PrimaryKeyType.PARTITIONED; -import static org.springframework.cassandra.core.PrimaryKeyType.CLUSTERED; +import static org.springframework.cassandra.core.PrimaryKeyType.*; +import static org.springframework.cassandra.core.cql.CqlStringUtils.*; import java.util.ArrayList; import java.util.List; @@ -28,8 +27,8 @@ import org.springframework.cassandra.core.keyspace.CreateTableSpecification; import org.springframework.cassandra.core.keyspace.Option; /** - * CQL generator for generating a CREATE TABLE statement. - * + * CQL generator for generating a {@code CREATE TABLE} statement. + * * @author Matthew T. Adams * @author Alex Shvid */ @@ -69,8 +68,8 @@ public class CreateTableCqlGenerator extends TableCqlGenerator partitionKeys = new ArrayList(); - List clusterKeys = new ArrayList(); + List partitionKeys = new ArrayList<>(); + List clusterKeys = new ArrayList<>(); for (ColumnSpecification col : spec().getColumns()) { col.toCql(cql).append(", "); diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/cql/generator/DropIndexCqlGenerator.java b/spring-cql/src/main/java/org/springframework/cassandra/core/cql/generator/DropIndexCqlGenerator.java index 8a01f4ffb..1e32ff136 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/cql/generator/DropIndexCqlGenerator.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/cql/generator/DropIndexCqlGenerator.java @@ -1,12 +1,12 @@ /* - * Copyright 2013-2014 the original author or authors. - * + * Copyright 2013-2017 the original author or authors. + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. @@ -15,13 +15,13 @@ */ package org.springframework.cassandra.core.cql.generator; -import static org.springframework.cassandra.core.cql.CqlStringUtils.noNull; +import static org.springframework.cassandra.core.cql.CqlStringUtils.*; import org.springframework.cassandra.core.keyspace.DropIndexSpecification; /** - * CQL generator for generating a DROP INDEX statement. - * + * CQL generator for generating a {@code DROP INDEX} statement. + * * @author Matthew T. Adams * @author David Webb */ diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/cql/generator/DropKeyspaceCqlGenerator.java b/spring-cql/src/main/java/org/springframework/cassandra/core/cql/generator/DropKeyspaceCqlGenerator.java index 813534065..46e04b3e9 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/cql/generator/DropKeyspaceCqlGenerator.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/cql/generator/DropKeyspaceCqlGenerator.java @@ -1,12 +1,12 @@ /* - * Copyright 2013-2014 the original author or authors. - * + * Copyright 2013-2017 the original author or authors. + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. @@ -15,13 +15,13 @@ */ package org.springframework.cassandra.core.cql.generator; -import static org.springframework.cassandra.core.cql.CqlStringUtils.noNull; +import static org.springframework.cassandra.core.cql.CqlStringUtils.*; import org.springframework.cassandra.core.keyspace.DropKeyspaceSpecification; /** - * CQL generator for generating a DROP TABLE statement. - * + * CQL generator for generating a {@code DROP TABLE} statement. + * * @author Matthew T. Adams */ public class DropKeyspaceCqlGenerator extends KeyspaceNameCqlGenerator { diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/cql/generator/DropTableCqlGenerator.java b/spring-cql/src/main/java/org/springframework/cassandra/core/cql/generator/DropTableCqlGenerator.java index d88ddc783..d0fd36a45 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/cql/generator/DropTableCqlGenerator.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/cql/generator/DropTableCqlGenerator.java @@ -1,12 +1,12 @@ /* - * Copyright 2013-2014 the original author or authors. - * + * Copyright 2013-2017 the original author or authors. + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. @@ -15,13 +15,13 @@ */ package org.springframework.cassandra.core.cql.generator; -import static org.springframework.cassandra.core.cql.CqlStringUtils.noNull; +import static org.springframework.cassandra.core.cql.CqlStringUtils.*; import org.springframework.cassandra.core.keyspace.DropTableSpecification; /** - * CQL generator for generating a DROP TABLE statement. - * + * CQL generator for generating a {@code DROP TABLE} statement. + * * @author Matthew T. Adams */ public class DropTableCqlGenerator extends TableNameCqlGenerator { diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/keyspace/AlterTableSpecification.java b/spring-cql/src/main/java/org/springframework/cassandra/core/keyspace/AlterTableSpecification.java index bcf875d7e..719cf4ad3 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/keyspace/AlterTableSpecification.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/keyspace/AlterTableSpecification.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2014 the original author or authors. + * Copyright 2013-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -66,7 +66,7 @@ public class AlterTableSpecification extends TableOptionsSpecification changes = new ArrayList(); + private List changes = new ArrayList<>(); /* * Adds a {@code DROP} to the list of column changes. diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/keyspace/AlterUserTypeSpecification.java b/spring-cql/src/main/java/org/springframework/cassandra/core/keyspace/AlterUserTypeSpecification.java index 407a2d009..ceeb93e06 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/keyspace/AlterUserTypeSpecification.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/keyspace/AlterUserTypeSpecification.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2016-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,7 +33,7 @@ import com.datastax.driver.core.DataType; */ public class AlterUserTypeSpecification extends UserTypeNameSpecification { - private final List changes = new ArrayList(); + private final List changes = new ArrayList<>(); /** * Entry point into the {@link AlterUserTypeSpecification}'s fluent API to alter a type. Convenient if imported diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/keyspace/ColumnSpecification.java b/spring-cql/src/main/java/org/springframework/cassandra/core/keyspace/ColumnSpecification.java index 49e84912f..a5ace6074 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/keyspace/ColumnSpecification.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/keyspace/ColumnSpecification.java @@ -31,8 +31,8 @@ import com.datastax.driver.core.DataType; * Builder class to specify columns. *

* Use {@link #name(String)} and {@link #type(String)} to set the name and type of the column, respectively. To specify - * a clustered PRIMARY KEY column, use {@link #clustered()} or {@link #clustered(Ordering)}. To specify - * that the PRIMARY KEY column is or is part of the partition key, use {@link #partitioned()} instead of + * a clustered {@code PRIMARY KEY} column, use {@link #clustered()} or {@link #clustered(Ordering)}. To specify that the + * {@code PRIMARY KEY} column is or is part of the partition key, use {@link #partitioned()} instead of * {@link #clustered()} or {@link #clustered(Ordering)}. * * @author Matthew T. Adams @@ -81,7 +81,7 @@ public class ColumnSpecification { /** * Identifies this column as a primary key column that is also part of a partition key. Sets the column's - * {@link #keyType} to {@link PrimaryKeyType#PARTITIONED} and its {@link #ordering} to null. + * {@link #keyType} to {@link PrimaryKeyType#PARTITIONED} and its {@link #ordering} to {@code null}. * * @return this */ @@ -91,8 +91,8 @@ public class ColumnSpecification { /** * Toggles the identification of this column as a primary key column that also is or is part of a partition key. Sets - * {@link #ordering} to null and, if the given boolean is true, then sets the column's - * {@link #keyType} to {@link PrimaryKeyType#PARTITIONED}, else sets it to null. + * {@link #ordering} to {@code null} and, if the given boolean is true, then sets the column's + * {@link #keyType} to {@link PrimaryKeyType#PARTITIONED}, else sets it to {@code null}. * * @return this */ @@ -123,9 +123,9 @@ public class ColumnSpecification { } /** - * Toggles the identification of this column as a clustered key column. If the given boolean is true, - * then sets the column's {@link #keyType} to {@link PrimaryKeyType#PARTITIONED} and {@link #ordering} to the given - * {@link Ordering} , else sets both {@link #keyType} and {@link #ordering} to null. + * Toggles the identification of this column as a clustered key column. If the given boolean is {@code true}, then + * sets the column's {@link #keyType} to {@link PrimaryKeyType#PARTITIONED} and {@link #ordering} to the given + * {@link Ordering} , else sets both {@link #keyType} and {@link #ordering} to {@code null}. * * @return this */ diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/keyspace/CreateIndexSpecification.java b/spring-cql/src/main/java/org/springframework/cassandra/core/keyspace/CreateIndexSpecification.java index 79215bfb8..1f2ee1aff 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/keyspace/CreateIndexSpecification.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/keyspace/CreateIndexSpecification.java @@ -22,7 +22,7 @@ import org.springframework.util.Assert; import org.springframework.util.StringUtils; /** - * Builder class to construct a CREATE INDEX specification. + * Builder class to construct a {@code CREATE INDEX} specification. * * @author Matthew T. Adams * @author David Webb @@ -61,7 +61,7 @@ public class CreateIndexSpecification extends IndexNameSpecificationIF NOT EXISTS clause. + * Causes the inclusion of an {@code IF NOT EXISTS} clause. * * @return this */ @@ -70,7 +70,7 @@ public class CreateIndexSpecification extends IndexNameSpecificationIF NOT EXISTS clause. + * Toggles the inclusion of an {@code IF NOT EXISTS} clause. * * @return this */ diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/keyspace/CreateKeyspaceSpecification.java b/spring-cql/src/main/java/org/springframework/cassandra/core/keyspace/CreateKeyspaceSpecification.java index 84ae88a85..9329e9cf2 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/keyspace/CreateKeyspaceSpecification.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/keyspace/CreateKeyspaceSpecification.java @@ -1,12 +1,12 @@ /* - * Copyright 2013-2014 the original author or authors. - * + * Copyright 2013-2017 the original author or authors. + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. @@ -16,7 +16,6 @@ package org.springframework.cassandra.core.keyspace; import org.springframework.cassandra.config.DataCenterReplication; -import org.springframework.cassandra.core.cql.CqlIdentifier; import org.springframework.cassandra.core.cql.KeyspaceIdentifier; import org.springframework.cassandra.core.keyspace.KeyspaceOption.ReplicationStrategy; import org.springframework.cassandra.core.util.MapBuilder; @@ -60,8 +59,8 @@ public class CreateKeyspaceSpecification extends KeyspaceSpecificationIF NOT EXISTS clause. - * + * Causes the inclusion of an {@code IF NOT EXISTS} clause. + * * @return this */ public CreateKeyspaceSpecification ifNotExists() { @@ -69,8 +68,8 @@ public class CreateKeyspaceSpecification extends KeyspaceSpecificationIF NOT EXISTS clause. - * + * Toggles the inclusion of an {@code IF NOT EXISTS} clause. + * * @return this */ public CreateKeyspaceSpecification ifNotExists(boolean ifNotExists) { @@ -103,7 +102,7 @@ public class CreateKeyspaceSpecification extends KeyspaceSpecificationCREATE TABLE specification. - * + * Builder class to construct a {@code CREATE TABLE} specification. + * * @author Matthew T. Adams */ public class CreateTableSpecification extends TableSpecification { @@ -56,8 +56,8 @@ public class CreateTableSpecification extends TableSpecificationIF NOT EXISTS clause. - * + * Causes the inclusion of an {@code IF NOT EXISTS} clause. + * * @return this */ public CreateTableSpecification ifNotExists() { @@ -65,8 +65,8 @@ public class CreateTableSpecification extends TableSpecificationIF NOT EXISTS clause. - * + * Toggles the inclusion of an {@code IF NOT EXISTS} clause. + * * @return this */ public CreateTableSpecification ifNotExists(boolean ifNotExists) { diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/keyspace/DropIndexSpecification.java b/spring-cql/src/main/java/org/springframework/cassandra/core/keyspace/DropIndexSpecification.java index 514f4772f..e205ba2bc 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/keyspace/DropIndexSpecification.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/keyspace/DropIndexSpecification.java @@ -1,12 +1,12 @@ /* - * Copyright 2013-2014 the original author or authors. - * + * Copyright 2013-2017 the original author or authors. + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. @@ -16,8 +16,8 @@ package org.springframework.cassandra.core.keyspace; /** - * Builder class that supports the construction of DROP INDEX specifications. - * + * Builder class that supports the construction of {@code DROP INDEX} specifications. + * * @author Matthew T. Adams * @author David Webb */ diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/keyspace/DropTableSpecification.java b/spring-cql/src/main/java/org/springframework/cassandra/core/keyspace/DropTableSpecification.java index 2518882aa..3c3e8db35 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/keyspace/DropTableSpecification.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/keyspace/DropTableSpecification.java @@ -1,12 +1,12 @@ /* - * Copyright 2013-2014 the original author or authors. - * + * Copyright 2013-2017 the original author or authors. + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. @@ -18,8 +18,8 @@ package org.springframework.cassandra.core.keyspace; import org.springframework.cassandra.core.cql.CqlIdentifier; /** - * Builder class that supports the construction of DROP TABLE specifications. - * + * Builder class that supports the construction of {@code DROP TABLE} specifications. + * * @author Matthew T. Adams */ public class DropTableSpecification extends TableNameSpecification { @@ -51,9 +51,8 @@ public class DropTableSpecification extends TableNameSpecificationdropTable().name(tableName). - * + * statically. This static method is shorter than the no-arg form, which would be {@code dropTable().name(tableName)}. + * * @param tableName The name of the table to drop. */ public static DropTableSpecification dropTable(CqlIdentifier tableName) { @@ -62,9 +61,8 @@ public class DropTableSpecification extends TableNameSpecificationdropTable().name(tableName). - * + * statically. This static method is shorter than the no-arg form, which would be {@code dropTable().name(tableName)}. + * * @param tableName The name of the table to drop. */ public static DropTableSpecification dropTable(String tableName) { diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/keyspace/KeyspaceOption.java b/spring-cql/src/main/java/org/springframework/cassandra/core/keyspace/KeyspaceOption.java index bccc96e2c..f311e912e 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/keyspace/KeyspaceOption.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/keyspace/KeyspaceOption.java @@ -1,12 +1,12 @@ /* - * Copyright 2013-2014 the original author or authors. - * + * Copyright 2013-2017 the original author or authors. + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. @@ -24,7 +24,7 @@ public enum KeyspaceOption implements Option { private Option delegate; - private KeyspaceOption(String name, Class type, boolean requiresValue, boolean escapesValue, boolean quotesValue) { + KeyspaceOption(String name, Class type, boolean requiresValue, boolean escapesValue, boolean quotesValue) { this.delegate = new DefaultOption(name, type, requiresValue, escapesValue, quotesValue); } @@ -70,7 +70,7 @@ public enum KeyspaceOption implements Option { /** * Known Replication Strategy options. - * + * * @author John McPeek */ public enum ReplicationStrategy { @@ -78,7 +78,7 @@ public enum KeyspaceOption implements Option { private String value; - private ReplicationStrategy(String value) { + ReplicationStrategy(String value) { this.value = value; } diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/keyspace/KeyspaceOptionsSpecification.java b/spring-cql/src/main/java/org/springframework/cassandra/core/keyspace/KeyspaceOptionsSpecification.java index a5458edd5..7b863c083 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/keyspace/KeyspaceOptionsSpecification.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/keyspace/KeyspaceOptionsSpecification.java @@ -1,12 +1,12 @@ /* - * Copyright 2013-2014 the original author or authors. - * + * Copyright 2013-2017 the original author or authors. + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. @@ -15,8 +15,7 @@ */ package org.springframework.cassandra.core.keyspace; -import static org.springframework.cassandra.core.cql.CqlStringUtils.escapeSingle; -import static org.springframework.cassandra.core.cql.CqlStringUtils.singleQuote; +import static org.springframework.cassandra.core.cql.CqlStringUtils.*; import java.util.Collections; import java.util.LinkedHashMap; @@ -26,21 +25,21 @@ import org.springframework.cassandra.core.cql.CqlStringUtils; /** * Abstract builder class to support the construction of table specifications that have table options, that is, those - * options normally specified by WITH ... AND .... + * options normally specified by {@code WITH ... AND ...}. *

* It is important to note that although this class depends on {@link KeyspaceOption} for convenient and typesafe use, * it ultimately stores its options in a Map for flexibility. This means that * {@link #with(KeyspaceOption)} and {@link #with(KeyspaceOption, Object)} delegate to * {@link #with(String, Object, boolean, boolean)}. This design allows the API to support new Cassandra options as they * are introduced without having to update the code immediately. - * + * * @author John McPeek * @param The subtype of the {@link KeyspaceOptionsSpecification}. */ public abstract class KeyspaceOptionsSpecification> extends KeyspaceActionSpecification> { - protected Map options = new LinkedHashMap(); + protected Map options = new LinkedHashMap<>(); @Override @SuppressWarnings("unchecked") @@ -49,8 +48,8 @@ public abstract class KeyspaceOptionsSpecificationwith(option, null). - * + * Convenience method that calls {@code with(option, null)}. + * * @return this */ public T with(KeyspaceOption option) { @@ -61,7 +60,7 @@ public abstract class KeyspaceOptionsSpecification - * Options that have null values are considered single string options where the name of the option is the + * Options that have {@code null} values are considered single string options where the name of the option is the * string to be used. Otherwise, the result of {@link Object#toString()} is considered to be the value of the option * with the given name. The value, after conversion to string, may have embedded single quotes escaped according to - * parameter escape and may be single-quoted according to parameter quote. - * + * parameter {@code escape} and may be single-quoted according to parameter quote. + * * @param name The name of the option - * @param value The value of the option. If null, the value is ignored and the option is considered to be + * @param value The value of the option. If {@code null}, the value is ignored and the option is considered to be * composed of only the name, otherwise the value's {@link Object#toString()} value is used. * @param escape Whether to escape the value via {@link CqlStringUtils#escapeSingle(Object)}. Ignored if given value * is an instance of a {@link Map}. diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/keyspace/Option.java b/spring-cql/src/main/java/org/springframework/cassandra/core/keyspace/Option.java index 9e6877c36..e318a08cf 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/keyspace/Option.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/keyspace/Option.java @@ -1,12 +1,12 @@ /* - * Copyright 2013-2014 the original author or authors. - * + * Copyright 2013-2017 the original author or authors. + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. @@ -17,7 +17,7 @@ package org.springframework.cassandra.core.keyspace; /** * Interface to represent option types. - * + * * @author Matthew T. Adams */ public interface Option { @@ -65,10 +65,9 @@ public interface Option { /** * First ensures that the given value is coerceable into the type expected by this option, then returns the result of * {@link Object#toString()} called on the given value. If this option is escaping quotes ({@link #escapesValue()} is - * true), then single quotes will be escaped, and if this option is quoting values ( - * {@link #quotesValue()} is true), then the value will be surrounded by single quotes. Given - * null, returns null. - * + * {@code true}), then single quotes will be escaped, and if this option is quoting values ( {@link #quotesValue()} is + * {@code true}), then the value will be surrounded by single quotes. Given {@code null}, returns null. + * * @see #escapesValue() * @see #quotesValue() */ diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/keyspace/TableDescriptor.java b/spring-cql/src/main/java/org/springframework/cassandra/core/keyspace/TableDescriptor.java index 0018ceed6..a46123a41 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/keyspace/TableDescriptor.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/keyspace/TableDescriptor.java @@ -1,12 +1,12 @@ /* - * Copyright 2013-2014 the original author or authors. - * + * Copyright 2013-2017 the original author or authors. + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. @@ -22,7 +22,7 @@ import org.springframework.cassandra.core.cql.CqlIdentifier; /** * Describes a table. - * + * * @author Matthew T. Adams * @author Alex Shvid */ @@ -41,22 +41,22 @@ public interface TableDescriptor { /** * Returns an unmodifiable list of all partition key columns. */ - public List getPartitionKeyColumns(); + List getPartitionKeyColumns(); /** * Returns an unmodifiable list of all primary key columns that are not also partition key columns. */ - public List getClusteredKeyColumns(); + List getClusteredKeyColumns(); /** * Returns an unmodifiable list of all partition and primary key columns. */ - public List getPrimaryKeyColumns(); + List getPrimaryKeyColumns(); /** * Returns an unmodifiable list of all non-key columns. */ - public List getNonKeyColumns(); + List getNonKeyColumns(); /** * Returns an unmodifiable {@link Map} of table options. diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/keyspace/TableOption.java b/spring-cql/src/main/java/org/springframework/cassandra/core/keyspace/TableOption.java index 8b8dc703e..6a41e2b12 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/keyspace/TableOption.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/keyspace/TableOption.java @@ -1,12 +1,12 @@ /* - * Copyright 2013-2014 the original author or authors. - * + * Copyright 2013-2017 the original author or authors. + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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. @@ -21,7 +21,7 @@ import java.util.Map; * Enumeration that represents all known table options. If a table option is not listed here, but is supported by * Cassandra, use the method {@link CreateTableSpecification#with(String, Object, boolean, boolean)} to write the raw * value. Implements {@link Option} via delegation, since {@link Enum}s can't extend anything. - * + * * @author Matthew T. Adams * @see CompactionOption * @see CompressionOption @@ -29,51 +29,51 @@ import java.util.Map; */ public enum TableOption implements Option { /** - * comment + * {@code comment} */ COMMENT("comment", String.class, true, true, true), /** - * COMPACT STORAGE + * {@code COMPACT STORAGE} */ COMPACT_STORAGE("COMPACT STORAGE", null, false, false, false), /** - * compaction. Value is a Map<CompactionOption,Object>. - * + * {@code compaction}. Value is a Map<CompactionOption,Object>. + * * @see CompactionOption */ COMPACTION("compaction", Map.class, true, false, false), /** - * compression. Value is a Map<CompressionOption,Object>. - * + * {@code compression}. Value is a Map<CompressionOption,Object>. + * * @see {@link CompressionOption} */ COMPRESSION("compression", Map.class, true, false, false), /** - * caching - * + * {@code caching} + * * @see CachingOption */ CACHING("caching", Map.class, true, false, false), /** - * bloom_filter_fp_chance + * {@code bloom_filter_fp_chance} */ BLOOM_FILTER_FP_CHANCE("bloom_filter_fp_chance", Double.class, true, false, false), /** - * read_repair_chance + * {@code read_repair_chance} */ READ_REPAIR_CHANCE("read_repair_chance", Double.class, true, false, false), /** - * dclocal_read_repair_chance + * {@code dclocal_read_repair_chance} */ DCLOCAL_READ_REPAIR_CHANCE("dclocal_read_repair_chance", Double.class, true, false, false), /** - * gc_grace_seconds + * {@code gc_grace_seconds} */ GC_GRACE_SECONDS("gc_grace_seconds", Long.class, true, false, false); private Option delegate; - private TableOption(String name, Class type, boolean requiresValue, boolean escapesValue, boolean quotesValue) { + TableOption(String name, Class type, boolean requiresValue, boolean escapesValue, boolean quotesValue) { this.delegate = new DefaultOption(name, type, requiresValue, escapesValue, quotesValue); } @@ -129,7 +129,7 @@ public enum TableOption implements Option { /** * Known KeyCaching Options - * + * * @author David Webb * @since 1.2.0 * @@ -140,7 +140,7 @@ public enum TableOption implements Option { private String value; - private KeyCachingOption(String value) { + KeyCachingOption(String value) { this.value = value; } @@ -156,7 +156,7 @@ public enum TableOption implements Option { /** * Known caching options. - * + * * @author Matthew T. Adams * @author David Webb * @since 1.2.0 @@ -169,7 +169,7 @@ public enum TableOption implements Option { private Option delegate; - private CachingOption(String name, Class type, boolean requiresValue, boolean escapesValue, boolean quotesValue) { + CachingOption(String name, Class type, boolean requiresValue, boolean escapesValue, boolean quotesValue) { this.delegate = new DefaultOption(name, type, requiresValue, escapesValue, quotesValue); } @@ -227,51 +227,51 @@ public enum TableOption implements Option { /** * Known compaction options. - * + * * @author Matthew T. Adams */ public enum CompactionOption implements Option { /** - * class + * {@code class} */ CLASS("class", String.class, true, false, true), /** - * tombstone_threshold + * {@code tombstone_threshold} */ TOMBSTONE_THRESHOLD("tombstone_threshold", Double.class, true, false, false), /** - * tombstone_compaction_interval + * {@code tombstone_compaction_interval} */ TOMBSTONE_COMPACTION_INTERVAL("tombstone_compaction_interval", Double.class, true, false, false), /** - * min_sstable_size + * {@code min_sstable_size} */ MIN_SSTABLE_SIZE("min_sstable_size", Long.class, true, false, false), /** - * min_threshold + * {@code min_threshold} */ MIN_THRESHOLD("min_threshold", Long.class, true, false, false), /** - * max_threshold + * {@code max_threshold} */ MAX_THRESHOLD("max_threshold", Long.class, true, false, false), /** - * bucket_low + * {@code bucket_low} */ BUCKET_LOW("bucket_low", Double.class, true, false, false), /** - * bucket_high + * {@code bucket_high} */ BUCKET_HIGH("bucket_high", Double.class, true, false, false), /** - * sstable_size_in_mb + * {@code sstable_size_in_mb} */ SSTABLE_SIZE_IN_MB("sstable_size_in_mb", Long.class, true, false, false); private Option delegate; - private CompactionOption(String name, Class type, boolean requiresValue, boolean escapesValue, - boolean quotesValue) { + CompactionOption(String name, Class type, boolean requiresValue, boolean escapesValue, + boolean quotesValue) { this.delegate = new DefaultOption(name, type, requiresValue, escapesValue, quotesValue); } @@ -328,27 +328,27 @@ public enum TableOption implements Option { /** * Known compression options. - * + * * @author Matthew T. Adams */ public enum CompressionOption implements Option { /** - * sstable_compression + * {@code sstable_compression} */ SSTABLE_COMPRESSION("sstable_compression", String.class, true, false, true), /** - * chunk_length_kb + * {@code chunk_length_kb} */ CHUNK_LENGTH_KB("chunk_length_kb", Long.class, true, false, false), /** - * crc_check_chance + * {@code crc_check_chance} */ CRC_CHECK_CHANCE("crc_check_chance", Double.class, true, false, false); private Option delegate; - private CompressionOption(String name, Class type, boolean requiresValue, boolean escapesValue, - boolean quotesValue) { + CompressionOption(String name, Class type, boolean requiresValue, boolean escapesValue, + boolean quotesValue) { this.delegate = new DefaultOption(name, type, requiresValue, escapesValue, quotesValue); } diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/keyspace/TableOptionsSpecification.java b/spring-cql/src/main/java/org/springframework/cassandra/core/keyspace/TableOptionsSpecification.java index b74a42fcb..81ce61d8e 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/keyspace/TableOptionsSpecification.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/keyspace/TableOptionsSpecification.java @@ -1,12 +1,12 @@ /* - * Copyright 2013-2014 the original author or authors. - * + * Copyright 2013-2017 the original author or authors. + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. @@ -15,8 +15,7 @@ */ package org.springframework.cassandra.core.keyspace; -import static org.springframework.cassandra.core.cql.CqlStringUtils.escapeSingle; -import static org.springframework.cassandra.core.cql.CqlStringUtils.singleQuote; +import static org.springframework.cassandra.core.cql.CqlStringUtils.*; import java.util.Collections; import java.util.LinkedHashMap; @@ -27,21 +26,21 @@ import org.springframework.cassandra.core.cql.CqlStringUtils; /** * Abstract builder class to support the construction of table specifications that have table options, that is, those - * options normally specified by WITH ... AND .... + * options normally specified by {@code WITH ... AND ...}. *

* It is important to note that although this class depends on {@link TableOption} for convenient and typesafe use, it * ultimately stores its options in a Map for flexibility. This means that * {@link #with(TableOption)} and {@link #with(TableOption, Object)} delegate to * {@link #with(String, Object, boolean, boolean)}. This design allows the API to support new Cassandra options as they * are introduced without having to update the code immediately. - * + * * @author Matthew T. Adams * @param The subtype of the {@link TableOptionsSpecification}. */ public abstract class TableOptionsSpecification> extends TableNameSpecification> { - protected Map options = new LinkedHashMap(); + protected Map options = new LinkedHashMap<>(); @Override @SuppressWarnings("unchecked") @@ -56,8 +55,8 @@ public abstract class TableOptionsSpecificationwith(option, null). - * + * Convenience method that calls {@code with(option, null)}. + * * @return this */ public T with(TableOption option) { @@ -68,7 +67,7 @@ public abstract class TableOptionsSpecification - * Options that have null values are considered single string options where the name of the option is the + * Options that have {@code null} values are considered single string options where the name of the option is the * string to be used. Otherwise, the result of {@link Object#toString()} is considered to be the value of the option * with the given name. The value, after conversion to string, may have embedded single quotes escaped according to - * parameter escape and may be single-quoted according to parameter quote. - * + * parameter {@code escape} and may be single-quoted according to parameter quote. + * * @param name The name of the option - * @param value The value of the option. If null, the value is ignored and the option is considered to be + * @param value The value of the option. If {@code null}, the value is ignored and the option is considered to be * composed of only the name, otherwise the value's {@link Object#toString()} value is used. * @param escape Whether to escape the value via {@link CqlStringUtils#escapeSingle(Object)}. Ignored if given value * is an instance of a {@link Map}. diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/keyspace/TableSpecification.java b/spring-cql/src/main/java/org/springframework/cassandra/core/keyspace/TableSpecification.java index 02684f73a..b7374896e 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/keyspace/TableSpecification.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/keyspace/TableSpecification.java @@ -43,22 +43,22 @@ public class TableSpecification extends TableOptionsSpecification columns = new ArrayList(); + private List columns = new ArrayList<>(); /** * List of only those columns that comprise the partition key. */ - private List partitionKeyColumns = new ArrayList(); + private List partitionKeyColumns = new ArrayList<>(); /** * List of only those columns that comprise the primary key that are not also part of the partition key. */ - private List clusteredKeyColumns = new ArrayList(); + private List clusteredKeyColumns = new ArrayList<>(); /** * List of only those columns that are not partition or primary key columns. */ - private List nonKeyColumns = new ArrayList(); + private List nonKeyColumns = new ArrayList<>(); /** * Adds the given non-key column to the table. Must be specified after all primary key columns. @@ -280,7 +280,7 @@ public class TableSpecification extends TableOptionsSpecification getPrimaryKeyColumns() { - ArrayList primaryKeyColumns = new ArrayList(); + ArrayList primaryKeyColumns = new ArrayList<>(); primaryKeyColumns.addAll(partitionKeyColumns); primaryKeyColumns.addAll(clusteredKeyColumns); diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/keyspace/UserTypeSpecification.java b/spring-cql/src/main/java/org/springframework/cassandra/core/keyspace/UserTypeSpecification.java index 75177c684..4b45ba477 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/keyspace/UserTypeSpecification.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/keyspace/UserTypeSpecification.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2016-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,7 +36,7 @@ import com.datastax.driver.core.DataType; */ public class UserTypeSpecification> extends UserTypeNameSpecification { - private final List fields = new ArrayList(); + private final List fields = new ArrayList<>(); /** * Adds the given field to the type. diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/session/ReactiveResultSet.java b/spring-cql/src/main/java/org/springframework/cassandra/core/session/ReactiveResultSet.java index 87ee5ac6f..a550f1697 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/session/ReactiveResultSet.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/session/ReactiveResultSet.java @@ -1,5 +1,5 @@ /* - * Copyright 2017 the original author or authors. + * Copyright 2016-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -63,7 +63,7 @@ public interface ReactiveResultSet { * * @return the columns returned in this ResultSet. */ - public ColumnDefinitions getColumnDefinitions(); + ColumnDefinitions getColumnDefinitions(); /** * If the query that produced this ResultSet was a conditional update, return whether it was successfully applied. @@ -79,7 +79,7 @@ public interface ReactiveResultSet { * @return if the query was a conditional update, whether it was applied. {@code true} for other types of queries. * @see CASSANDRA-7337 */ - public boolean wasApplied(); + boolean wasApplied(); /** * Returns information on the execution of the last query made for this result set. diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/support/EmptyResultSet.java b/spring-cql/src/main/java/org/springframework/cassandra/core/support/EmptyResultSet.java deleted file mode 100644 index 180d56c73..000000000 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/support/EmptyResultSet.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright 2013-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.cassandra.core.support; - -import java.util.Collections; -import java.util.Iterator; -import java.util.List; - -import com.datastax.driver.core.ExecutionInfo; -import com.datastax.driver.core.ResultSet; -import com.datastax.driver.core.Row; - -/** - * An empty {@link com.datastax.driver.core.ResultSet} implementation - * - * @author John Blum - * @see org.springframework.cassandra.core.support.ResultSetAdapter - * @see com.datastax.driver.core.ResultSet - * @since 1.5.0 - */ -public class EmptyResultSet extends ResultSetAdapter { - - protected static final EmptyResultSet INSTANCE = new EmptyResultSet(); - - /** - * Returns the given {@link ResultSet} if not null, otherwise returns an empty {@link ResultSet}. - * - * @param resultSet {@link ResultSet} to evaluate for {@literal null}. - * @return the given {@link ResultSet} if not null, otherwise return an empty {@link ResultSet}. - * @see com.datastax.driver.core.ResultSet - */ - public static ResultSet nullSafeResultSet(ResultSet resultSet) { - return (resultSet != null ? resultSet : EmptyResultSet.INSTANCE); - } - - /* - * (non-Javadoc) - * @see com.datastax.driver.core.ResultSet#isExhausted() - */ - @Override - public boolean isExhausted() { - return true; - } - - /* - * (non-Javadoc) - * @see com.datastax.driver.core.ResultSet#isFullyFetched() - */ - @Override - public boolean isFullyFetched() { - return true; - } - - /* - * (non-Javadoc) - * @see com.datastax.driver.core.ResultSet#getAvailableWithoutFetching() - */ - @Override - public int getAvailableWithoutFetching() { - return 0; - } - - /* - * (non-Javadoc) - * @see com.datastax.driver.core.ResultSet#getAllExecutionInfo() - */ - @Override - public List getAllExecutionInfo() { - return Collections.emptyList(); - } - - /* - * (non-Javadoc) - * @see com.datastax.driver.core.ResultSet#getExecutionInfo() - */ - @Override - public ExecutionInfo getExecutionInfo() { - return null; - } - - /* - * (non-Javadoc) - * @see com.datastax.driver.core.ResultSet#all() - */ - @Override - public List all() { - return Collections.emptyList(); - } - - /* - * (non-Javadoc) - * @see com.datastax.driver.core.ResultSet#iterator() - */ - @Override - public Iterator iterator() { - return Collections.emptyIterator(); - } - - /* - * (non-Javadoc) - * @see com.datastax.driver.core.ResultSet#one() - */ - @Override - public Row one() { - return null; - } -} diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/support/ResultSetAdapter.java b/spring-cql/src/main/java/org/springframework/cassandra/core/support/ResultSetAdapter.java deleted file mode 100644 index 62c94a19b..000000000 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/support/ResultSetAdapter.java +++ /dev/null @@ -1,137 +0,0 @@ -/* - * Copyright 2013-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.cassandra.core.support; - -import java.util.Iterator; -import java.util.List; - -import com.datastax.driver.core.ColumnDefinitions; -import com.datastax.driver.core.ExecutionInfo; -import com.datastax.driver.core.ResultSet; -import com.datastax.driver.core.Row; -import com.google.common.util.concurrent.ListenableFuture; - -/** - * An Adapter class to simply implementations of the {@link ResultSet} interface. - * - * @author John Blum - * @see com.datastax.driver.core.ResultSet - * @since 1.5.0 - */ -public class ResultSetAdapter implements ResultSet { - - private static final String NOT_SUPPORTED = "Not Supported"; - - /* - * (non-Javadoc) - * @see com.datastax.driver.core.ResultSet#isExhausted() - */ - @Override - public boolean isExhausted() { - throw new UnsupportedOperationException(NOT_SUPPORTED); - } - - /* - * (non-Javadoc) - * @see com.datastax.driver.core.ResultSet#isFullyFetched() - */ - @Override - public boolean isFullyFetched() { - throw new UnsupportedOperationException(NOT_SUPPORTED); - } - - /* - * (non-Javadoc) - * @see com.datastax.driver.core.ResultSet#getAvailableWithoutFetching() - */ - @Override - public int getAvailableWithoutFetching() { - throw new UnsupportedOperationException(NOT_SUPPORTED); - } - - /* - * (non-Javadoc) - * @see com.datastax.driver.core.ResultSet#getColumnDefinitions() - */ - @Override - public ColumnDefinitions getColumnDefinitions() { - throw new UnsupportedOperationException(NOT_SUPPORTED); - } - - /* - * (non-Javadoc) - * @see com.datastax.driver.core.ResultSet#getAllExecutionInfo() - */ - @Override - public List getAllExecutionInfo() { - throw new UnsupportedOperationException(NOT_SUPPORTED); - } - - /* - * (non-Javadoc) - * @see com.datastax.driver.core.ResultSet#getExecutionInfo() - */ - @Override - public ExecutionInfo getExecutionInfo() { - throw new UnsupportedOperationException(NOT_SUPPORTED); - } - - /* - * (non-Javadoc) - * @see com.datastax.driver.core.ResultSet#all() - */ - @Override - public List all() { - throw new UnsupportedOperationException(NOT_SUPPORTED); - } - - /* - * (non-Javadoc) - * @see com.datastax.driver.core.ResultSet#fetchMoreResults() - */ - @Override - public ListenableFuture fetchMoreResults() { - throw new UnsupportedOperationException(NOT_SUPPORTED); - } - - /* - * (non-Javadoc) - * @see com.datastax.driver.core.ResultSet#iterator() - */ - @Override - public Iterator iterator() { - throw new UnsupportedOperationException(NOT_SUPPORTED); - } - - /* - * (non-Javadoc) - * @see com.datastax.driver.core.ResultSet#one() - */ - @Override - public Row one() { - throw new UnsupportedOperationException(NOT_SUPPORTED); - } - - /* - * (non-Javadoc) - * @see com.datastax.driver.core.ResultSet#wasApplied() - */ - @Override - public boolean wasApplied() { - throw new UnsupportedOperationException(NOT_SUPPORTED); - } -} diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/util/CollectionUtils.java b/spring-cql/src/main/java/org/springframework/cassandra/core/util/CollectionUtils.java deleted file mode 100644 index 301e48a57..000000000 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/util/CollectionUtils.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright 2013-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. - * 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.cassandra.core.util; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -public abstract class CollectionUtils extends org.springframework.util.CollectionUtils { - - public static Object[] toArray(Iterable iterable) { - return toList(iterable).toArray(); - } - - public static List toList(T... elements) { - List list = Collections.emptyList(); - - if (elements != null) { - list = new ArrayList(elements.length); - Collections.addAll(list, elements); - } - - return list; - } - - public static List toList(Iterable iterable) { - if (!(iterable instanceof List)) { - List list = new ArrayList(); - - if (iterable != null) { - for (T element : iterable) { - list.add(element); - } - } - - iterable = list; - } - - return (List) iterable; - } - -} diff --git a/spring-cql/src/main/java/org/springframework/cassandra/core/util/MapBuilder.java b/spring-cql/src/main/java/org/springframework/cassandra/core/util/MapBuilder.java index 5b5c91d46..55bde956a 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/core/util/MapBuilder.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/core/util/MapBuilder.java @@ -1,12 +1,12 @@ /* - * Copyright 2013-2014 the original author or authors. - * + * Copyright 2013-2017 the original author or authors. + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. @@ -16,22 +16,47 @@ package org.springframework.cassandra.core.util; import java.util.Collection; +import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; +import org.springframework.util.Assert; + /** * Builder for maps, which also conveniently implements {@link Map} via delegation for convenience so you don't have to * actually {@link #build()} it. - * + * * @author Matthew T. Adams + * @author Mark Paluch * @param The key type of the map. * @param The value type of the map. */ public class MapBuilder implements Map { + private Map map; + /** - * Factory method to construct a new MapBuilder<Object,Object>. Convenient if imported statically. + * Create a new {@link MapBuilder}. + */ + public MapBuilder() { + this(Collections.emptyMap()); + } + + /** + * Create a new instance with a copy of the given map. + * + * @param source must not be {@literal null} + */ + public MapBuilder(Map source) { + + Assert.notNull(source, "Source map must not be null"); + + this.map = new LinkedHashMap<>(source); + } + + /** + * Factory method to construct a new {@code MapBuilder}. Convenient if imported statically. */ public static MapBuilder map() { return map(Object.class, Object.class); @@ -41,32 +66,19 @@ public class MapBuilder implements Map { * Factory method to construct a new builder with the given key & value types. Convenient if imported statically. */ public static MapBuilder map(Class keyType, Class valueType) { - return new MapBuilder(); + return new MapBuilder<>(); } /** * Factory method to construct a new builder with a shallow copy of the given map. Convenient if imported statically. */ public static MapBuilder map(Map source) { - return new MapBuilder(source); - } - - private Map map; - - public MapBuilder() { - this(new LinkedHashMap()); + return new MapBuilder<>(source); } /** - * Constructs a new instance with a copy of the given map. - */ - public MapBuilder(Map source) { - this.map = new LinkedHashMap(source); - } - - /** - * Adds an entry to this map, then returns this. - * + * Add an entry to this map, then returns {@code this}. + * * @return this */ public MapBuilder entry(K key, V value) { @@ -75,79 +87,121 @@ public class MapBuilder implements Map { } /** - * Returns a new map based on the current state of this builder's map. - * + * Return a new map based on the current state of this builder's map. + * * @return A new Map with this builder's map's current content. */ public Map build() { - return new LinkedHashMap(map); + return new LinkedHashMap<>(map); } + /* (non-Javadoc) + * @see java.util.Map#size() + */ @Override public int size() { return map.size(); } + /* (non-Javadoc) + * @see java.util.Map#isEmpty() + */ @Override public boolean isEmpty() { return map.isEmpty(); } + /* (non-Javadoc) + * @see java.util.Map#containsKey(java.lang.Object) + */ @Override public boolean containsKey(Object key) { return map.containsKey(key); } + /* (non-Javadoc) + * @see java.util.Map#containsValue(java.lang.Object) + */ @Override public boolean containsValue(Object value) { return map.containsValue(value); } + /* (non-Javadoc) + * @see java.util.Map#get(java.lang.Object) + */ @Override public V get(Object key) { return map.get(key); } + /* (non-Javadoc) + * @see java.util.Map#put(java.lang.Object, java.lang.Object) + */ @Override public V put(K key, V value) { return map.put(key, value); } + /* (non-Javadoc) + * @see java.util.Map#remove(java.lang.Object) + */ @Override public V remove(Object key) { return map.remove(key); } + /* (non-Javadoc) + * @see java.util.Map#putAll(java.util.Map) + */ @Override public void putAll(Map m) { map.putAll(m); } + /* (non-Javadoc) + * @see java.util.Map#clear() + */ @Override public void clear() { map.clear(); } + /* (non-Javadoc) + * @see java.util.Map#keySet() + */ @Override public Set keySet() { return map.keySet(); } + /* (non-Javadoc) + * @see java.util.Map#values() + */ @Override public Collection values() { return map.values(); } + /* (non-Javadoc) + * @see java.util.Map#entrySet() + */ @Override public Set> entrySet() { return map.entrySet(); } + /* (non-Javadoc) + * @see java.lang.Object#equals(java.lang.Object) + */ @Override public boolean equals(Object o) { return map.equals(o); } + /* (non-Javadoc) + * @see java.lang.Object#hashCode() + */ @Override public int hashCode() { return map.hashCode(); diff --git a/spring-cql/src/main/java/org/springframework/cassandra/support/CassandraAccessor.java b/spring-cql/src/main/java/org/springframework/cassandra/support/CassandraAccessor.java index 1a2be2731..e8c6d3962 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/support/CassandraAccessor.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/support/CassandraAccessor.java @@ -16,6 +16,7 @@ package org.springframework.cassandra.support; import java.util.Map; +import java.util.Optional; import java.util.stream.StreamSupport; import org.slf4j.Logger; @@ -377,7 +378,11 @@ public class CassandraAccessor implements InitializingBean { * @see CqlProvider */ protected static String toCql(Object cqlProvider) { - return (cqlProvider instanceof CqlProvider ? ((CqlProvider) cqlProvider).getCql() : null); + return Optional.ofNullable(cqlProvider) // + .filter(o -> o instanceof CqlProvider) // + .map(o -> (CqlProvider) o) // + .map(CqlProvider::getCql) // + .orElse(null); } protected void logDebug(String logMessage, Object... array) { @@ -444,7 +449,8 @@ public class CassandraAccessor implements InitializingBean { } /* (non-Javadoc) - * @see org.springframework.cassandra.core.ResultSetExtractor#extractData(com.datastax.driver.core.ResultSet) + * + @see org.springframework.cassandra.core.ResultSetExtractor#extractData(com.datastax.driver.core.ResultSet) */ @Override public Object extractData(ResultSet resultSet) { diff --git a/spring-cql/src/main/java/org/springframework/cassandra/support/exception/CassandraConnectionFailureException.java b/spring-cql/src/main/java/org/springframework/cassandra/support/exception/CassandraConnectionFailureException.java index 6f62ebc1e..e8aba45d7 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/support/exception/CassandraConnectionFailureException.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/support/exception/CassandraConnectionFailureException.java @@ -1,12 +1,12 @@ /* - * Copyright 2013-2014 the original author or authors. - * + * Copyright 2013-2017 the original author or authors. + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. @@ -24,14 +24,14 @@ import org.springframework.dao.DataAccessResourceFailureException; /** * Spring data access exception for Cassandra when no host is available. - * + * * @author Matthew T. Adams */ public class CassandraConnectionFailureException extends DataAccessResourceFailureException { private static final long serialVersionUID = 6299912054261646552L; - private final Map messagesByHost = new HashMap(); + private final Map messagesByHost = new HashMap<>(); public CassandraConnectionFailureException(Map map, String msg, Throwable cause) { super(msg, cause); diff --git a/spring-cql/src/main/java/org/springframework/cassandra/support/exception/CassandraSchemaElementExistsException.java b/spring-cql/src/main/java/org/springframework/cassandra/support/exception/CassandraSchemaElementExistsException.java index a99928f53..a43d9b113 100644 --- a/spring-cql/src/main/java/org/springframework/cassandra/support/exception/CassandraSchemaElementExistsException.java +++ b/spring-cql/src/main/java/org/springframework/cassandra/support/exception/CassandraSchemaElementExistsException.java @@ -1,12 +1,12 @@ /* - * Copyright 2013-2014 the original author or authors. - * + * Copyright 2013-2017 the original author or authors. + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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. @@ -19,7 +19,7 @@ import org.springframework.dao.NonTransientDataAccessException; /** * Spring data access exception for when Cassandra schema element being created already exists. - * + * * @author Matthew T. Adams */ public class CassandraSchemaElementExistsException extends NonTransientDataAccessException { @@ -27,7 +27,7 @@ public class CassandraSchemaElementExistsException extends NonTransientDataAcces private static final long serialVersionUID = 7798361273692300162L; public enum ElementType { - KEYSPACE, TABLE, COLUMN, INDEX; + KEYSPACE, TABLE, COLUMN, INDEX } private String elementName; diff --git a/spring-cql/src/test/java/org/springframework/cassandra/config/CassandraCqlSessionFactoryBeanUnitTests.java b/spring-cql/src/test/java/org/springframework/cassandra/config/CassandraCqlSessionFactoryBeanUnitTests.java index be6a0dbef..668420ea2 100755 --- a/spring-cql/src/test/java/org/springframework/cassandra/config/CassandraCqlSessionFactoryBeanUnitTests.java +++ b/spring-cql/src/test/java/org/springframework/cassandra/config/CassandraCqlSessionFactoryBeanUnitTests.java @@ -253,7 +253,7 @@ public class CassandraCqlSessionFactoryBeanUnitTests { @Test // DATACASS-219 public void startupScriptsAreImmutable() { - List startupScripts = new ArrayList(Collections.singletonList("/path/to/startup.cql")); + List startupScripts = new ArrayList<>(Collections.singletonList("/path/to/startup.cql")); factoryBean.setStartupScripts(startupScripts); @@ -295,7 +295,7 @@ public class CassandraCqlSessionFactoryBeanUnitTests { @Test // DATACASS-219 public void shutdownScriptsAreImmutable() { - List shutdownScripts = new ArrayList(Collections.singletonList("/path/to/shutdown.cql")); + List shutdownScripts = new ArrayList<>(Collections.singletonList("/path/to/shutdown.cql")); factoryBean.setShutdownScripts(shutdownScripts); List actualShutdownScripts = factoryBean.getShutdownScripts(); diff --git a/spring-cql/src/test/java/org/springframework/cassandra/config/PoolingOptionsFactoryBeanUnitTests.java b/spring-cql/src/test/java/org/springframework/cassandra/config/PoolingOptionsFactoryBeanUnitTests.java index 944b0ae4a..7483ef0ad 100755 --- a/spring-cql/src/test/java/org/springframework/cassandra/config/PoolingOptionsFactoryBeanUnitTests.java +++ b/spring-cql/src/test/java/org/springframework/cassandra/config/PoolingOptionsFactoryBeanUnitTests.java @@ -69,7 +69,7 @@ public class PoolingOptionsFactoryBeanUnitTests { @Test @SuppressWarnings("unchecked") public void getObjectTypeReturnsPoolingOptionsClassWhenNotInitialized() { - assertThat((Class) poolingOptionsFactoryBean.getObjectType()).isEqualTo(PoolingOptions.class); + assertThat(poolingOptionsFactoryBean.getObjectType()).isEqualTo(PoolingOptions.class); } @Test diff --git a/spring-cql/src/test/java/org/springframework/cassandra/core/AsyncCqlTemplateIntegrationTests.java b/spring-cql/src/test/java/org/springframework/cassandra/core/AsyncCqlTemplateIntegrationTests.java index d7006e677..ad2bca03d 100644 --- a/spring-cql/src/test/java/org/springframework/cassandra/core/AsyncCqlTemplateIntegrationTests.java +++ b/spring-cql/src/test/java/org/springframework/cassandra/core/AsyncCqlTemplateIntegrationTests.java @@ -32,7 +32,7 @@ import com.datastax.driver.core.querybuilder.QueryBuilder; /** * Integration tests for {@link AsyncCqlTemplate}. - * + * * @author Mark Paluch */ public class AsyncCqlTemplateIntegrationTests extends AbstractKeyspaceCreatingIntegrationTest { @@ -149,7 +149,7 @@ public class AsyncCqlTemplateIntegrationTests extends AbstractKeyspaceCreatingIn List result = new ArrayList<>(); getUninterruptibly(template.query( - session -> new GuavaListenableFutureAdapter( + session -> new GuavaListenableFutureAdapter<>( session.prepareAsync("SELECT id FROM user WHERE id = ?;"), template.getExceptionTranslator()), ps -> ps.bind("WHITE"), row -> { result.add(row.getString(0)); diff --git a/spring-cql/src/test/java/org/springframework/cassandra/core/AsyncCqlTemplateUnitTests.java b/spring-cql/src/test/java/org/springframework/cassandra/core/AsyncCqlTemplateUnitTests.java index 2229a6295..bbaae6730 100644 --- a/spring-cql/src/test/java/org/springframework/cassandra/core/AsyncCqlTemplateUnitTests.java +++ b/spring-cql/src/test/java/org/springframework/cassandra/core/AsyncCqlTemplateUnitTests.java @@ -51,7 +51,7 @@ import com.google.common.util.concurrent.SettableFuture; /** * Unit tests for {@link AsyncCqlTemplate}. - * + * * @author Mark Paluch */ @RunWith(MockitoJUnitRunner.class) @@ -577,7 +577,7 @@ public class AsyncCqlTemplateUnitTests { when(session.executeAsync(boundStatement)).thenReturn(new TestResultSetFuture(resultSet)); when(resultSet.iterator()).thenReturn(Collections.singleton(row).iterator()); - ListenableFuture future = template.query(session -> new AsyncResult<>(preparedStatement), ps -> { + ListenableFuture future = template.query(session -> new AsyncResult(preparedStatement), ps -> { ps.bind("a", "b"); return boundStatement; }, rs -> rs); @@ -611,7 +611,7 @@ public class AsyncCqlTemplateUnitTests { when(preparedStatement.bind()).thenReturn(boundStatement); - ListenableFuture future = template.query(session -> new AsyncResult<>(preparedStatement), ps -> { + ListenableFuture future = template.query(session -> new AsyncResult(preparedStatement), ps -> { throw new NoHostAvailableException(Collections.emptyMap()); }, rs -> rs); @@ -633,7 +633,7 @@ public class AsyncCqlTemplateUnitTests { when(session.executeAsync(boundStatement)).thenReturn(resultSetFuture); - ListenableFuture future = template.query(session -> new AsyncResult<>(preparedStatement), ps -> { + ListenableFuture future = template.query(session -> new AsyncResult(preparedStatement), ps -> { ps.bind("a", "b"); return boundStatement; }, rs -> rs); diff --git a/spring-cql/src/test/java/org/springframework/cassandra/core/ConsistencyLevelResolverUnitTests.java b/spring-cql/src/test/java/org/springframework/cassandra/core/ConsistencyLevelResolverUnitTests.java index 12b0b75d3..e8210c168 100644 --- a/spring-cql/src/test/java/org/springframework/cassandra/core/ConsistencyLevelResolverUnitTests.java +++ b/spring-cql/src/test/java/org/springframework/cassandra/core/ConsistencyLevelResolverUnitTests.java @@ -30,7 +30,7 @@ import org.junit.runners.Parameterized.Parameters; /** * Unit tests for {@link ConsistencyLevelResolver}. - * + * * @author Mark Paluch */ @RunWith(Parameterized.class) @@ -48,7 +48,7 @@ public class ConsistencyLevelResolverUnitTests { @Parameters(name = "{0}") public static List parameters() { - Map expectations = new LinkedHashMap(); + Map expectations = new LinkedHashMap<>(); expectations.put(ConsistencyLevel.ALL, com.datastax.driver.core.ConsistencyLevel.ALL); expectations.put(ConsistencyLevel.ANY, com.datastax.driver.core.ConsistencyLevel.ANY); @@ -70,7 +70,7 @@ public class ConsistencyLevelResolverUnitTests { expectations.put(ConsistencyLevel.TWO, com.datastax.driver.core.ConsistencyLevel.TWO); expectations.put(ConsistencyLevel.THREE, com.datastax.driver.core.ConsistencyLevel.THREE); - List parameters = new ArrayList(); + List parameters = new ArrayList<>(); for (Entry entry : expectations.entrySet()) { parameters.add(new Object[] { entry.getKey(), entry.getValue() }); diff --git a/spring-cql/src/test/java/org/springframework/cassandra/core/CqlTemplateIntegrationTests.java b/spring-cql/src/test/java/org/springframework/cassandra/core/CqlTemplateIntegrationTests.java index 41689d455..ad435a966 100644 --- a/spring-cql/src/test/java/org/springframework/cassandra/core/CqlTemplateIntegrationTests.java +++ b/spring-cql/src/test/java/org/springframework/cassandra/core/CqlTemplateIntegrationTests.java @@ -30,7 +30,7 @@ import com.datastax.driver.core.querybuilder.QueryBuilder; /** * Integration tests for {@link CqlTemplate}. - * + * * @author Mark Paluch */ public class CqlTemplateIntegrationTests extends AbstractKeyspaceCreatingIntegrationTest { diff --git a/spring-cql/src/test/java/org/springframework/cassandra/core/SingleColumnRowMapperUnitTests.java b/spring-cql/src/test/java/org/springframework/cassandra/core/SingleColumnRowMapperUnitTests.java index c177ad54e..6875c99c3 100644 --- a/spring-cql/src/test/java/org/springframework/cassandra/core/SingleColumnRowMapperUnitTests.java +++ b/spring-cql/src/test/java/org/springframework/cassandra/core/SingleColumnRowMapperUnitTests.java @@ -32,7 +32,7 @@ import com.datastax.driver.core.Row; /** * Unit tests for {@link SingleColumnRowMapper}. - * + * * @author Mark Paluch * @soundtrack Kos Vs Michael Buffer - Go For It All (Rubberboot Mix) */ diff --git a/spring-cql/src/test/java/org/springframework/cassandra/core/cql/generator/AlterKeyspaceCqlGeneratorUnitTests.java b/spring-cql/src/test/java/org/springframework/cassandra/core/cql/generator/AlterKeyspaceCqlGeneratorUnitTests.java index 37a18e71d..0c6b00605 100755 --- a/spring-cql/src/test/java/org/springframework/cassandra/core/cql/generator/AlterKeyspaceCqlGeneratorUnitTests.java +++ b/spring-cql/src/test/java/org/springframework/cassandra/core/cql/generator/AlterKeyspaceCqlGeneratorUnitTests.java @@ -45,10 +45,7 @@ public class AlterKeyspaceCqlGeneratorUnitTests { private static void assertReplicationMap(Map replicationMap, String cql) { assertThat(cql.contains(" WITH replication = { ")).isTrue(); - for (Map.Entry entry : replicationMap.entrySet()) { - String keyValuePair = "'" + entry.getKey().getName() + "' : '" + entry.getValue().toString() + "'"; - assertThat(cql.contains(keyValuePair)).isTrue(); - } + replicationMap.entrySet().stream().map(entry -> "'" + entry.getKey().getName() + "' : '" + entry.getValue().toString() + "'").forEach(keyValuePair -> assertThat(cql.contains(keyValuePair)).isTrue()); } public static void assertDurableWrites(Boolean durableWrites, String cql) { @@ -66,7 +63,7 @@ public class AlterKeyspaceCqlGeneratorUnitTests { public String name = RandomKeySpaceName.create(); public Boolean durableWrites = true; - public Map replicationMap = new HashMap(); + public Map replicationMap = new HashMap<>(); @Override public AlterKeyspaceSpecification specification() { @@ -99,7 +96,7 @@ public class AlterKeyspaceCqlGeneratorUnitTests { public String name = "mytable"; public Boolean durableWrites = true; - public Map replicationMap = new HashMap(); + public Map replicationMap = new HashMap<>(); @Override public AlterKeyspaceSpecification specification() { diff --git a/spring-cql/src/test/java/org/springframework/cassandra/core/cql/generator/AlterTableCqlGeneratorIntegrationTests.java b/spring-cql/src/test/java/org/springframework/cassandra/core/cql/generator/AlterTableCqlGeneratorIntegrationTests.java index c2625ecb7..a7d89da0c 100755 --- a/spring-cql/src/test/java/org/springframework/cassandra/core/cql/generator/AlterTableCqlGeneratorIntegrationTests.java +++ b/spring-cql/src/test/java/org/springframework/cassandra/core/cql/generator/AlterTableCqlGeneratorIntegrationTests.java @@ -140,7 +140,7 @@ public class AlterTableCqlGeneratorIntegrationTests extends AbstractKeyspaceCrea session.execute("CREATE TABLE users (user_name varchar PRIMARY KEY);"); - Map cachingMap = new LinkedHashMap(); + Map cachingMap = new LinkedHashMap<>(); cachingMap.put(CachingOption.KEYS, KeyCachingOption.NONE); cachingMap.put(CachingOption.ROWS_PER_PARTITION, "15"); diff --git a/spring-cql/src/test/java/org/springframework/cassandra/core/cql/generator/AlterTableCqlGeneratorUnitTests.java b/spring-cql/src/test/java/org/springframework/cassandra/core/cql/generator/AlterTableCqlGeneratorUnitTests.java index 0c92ea0d4..57162012d 100755 --- a/spring-cql/src/test/java/org/springframework/cassandra/core/cql/generator/AlterTableCqlGeneratorUnitTests.java +++ b/spring-cql/src/test/java/org/springframework/cassandra/core/cql/generator/AlterTableCqlGeneratorUnitTests.java @@ -113,7 +113,7 @@ public class AlterTableCqlGeneratorUnitTests { @Test // DATACASS-192 public void alterTableAddCaching() { - Map cachingMap = new LinkedHashMap(); + Map cachingMap = new LinkedHashMap<>(); cachingMap.put(CachingOption.KEYS, KeyCachingOption.NONE); cachingMap.put(CachingOption.ROWS_PER_PARTITION, "15"); diff --git a/spring-cql/src/test/java/org/springframework/cassandra/core/cql/generator/CreateKeyspaceCqlGeneratorUnitTests.java b/spring-cql/src/test/java/org/springframework/cassandra/core/cql/generator/CreateKeyspaceCqlGeneratorUnitTests.java index 7377e6c3f..a6f66fa65 100755 --- a/spring-cql/src/test/java/org/springframework/cassandra/core/cql/generator/CreateKeyspaceCqlGeneratorUnitTests.java +++ b/spring-cql/src/test/java/org/springframework/cassandra/core/cql/generator/CreateKeyspaceCqlGeneratorUnitTests.java @@ -124,7 +124,7 @@ public class CreateKeyspaceCqlGeneratorUnitTests { public String name = RandomKeySpaceName.create(); public Boolean durableWrites = false; - public Map replicationMap = new HashMap(); + public Map replicationMap = new HashMap<>(); @Override public CreateKeyspaceSpecification specification() { diff --git a/spring-cql/src/test/java/org/springframework/cassandra/core/cql/generator/CreateTableCqlGeneratorUnitTests.java b/spring-cql/src/test/java/org/springframework/cassandra/core/cql/generator/CreateTableCqlGeneratorUnitTests.java index 4b6380eed..4da6abb2c 100755 --- a/spring-cql/src/test/java/org/springframework/cassandra/core/cql/generator/CreateTableCqlGeneratorUnitTests.java +++ b/spring-cql/src/test/java/org/springframework/cassandra/core/cql/generator/CreateTableCqlGeneratorUnitTests.java @@ -24,6 +24,7 @@ import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.stream.Collectors; import org.junit.Test; import org.slf4j.Logger; @@ -224,9 +225,9 @@ public class CreateTableCqlGeneratorUnitTests { public Boolean replcateOnWrite = Boolean.FALSE; public Long gcGraceSeconds = 600l; public String comment = "This is My Table"; - public Map compactionMap = new LinkedHashMap(); - public Map compressionMap = new LinkedHashMap(); - public Map cachingMap = new LinkedHashMap(); + public Map compactionMap = new LinkedHashMap<>(); + public Map compressionMap = new LinkedHashMap<>(); + public Map cachingMap = new LinkedHashMap<>(); @Override public CreateTableSpecification specification() { @@ -277,12 +278,11 @@ public class CreateTableCqlGeneratorUnitTests { public static final List FUNKY_LEGAL_NAMES; static { - List funkies = new ArrayList(Arrays.asList(new String[] { /* TODO */ })); + List funkies = new ArrayList<>(Arrays.asList(new String[]{ /* TODO */})); // TODO: should these work? "a \"\" x", "a\"\"\"\"x", "a b" - for (ReservedKeyword funky : ReservedKeyword.values()) { - funkies.add(funky.name()); - } - FUNKY_LEGAL_NAMES = Collections.unmodifiableList(funkies); + FUNKY_LEGAL_NAMES = Collections.unmodifiableList(Arrays.stream(ReservedKeyword.values()) // + .map(Enum::name) // + .collect(Collectors.toList())); } @Test diff --git a/spring-cql/src/test/java/org/springframework/cassandra/core/support/EmptyResultSetUnitTests.java b/spring-cql/src/test/java/org/springframework/cassandra/core/support/EmptyResultSetUnitTests.java deleted file mode 100644 index 9dd17d426..000000000 --- a/spring-cql/src/test/java/org/springframework/cassandra/core/support/EmptyResultSetUnitTests.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * 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.cassandra.core.support; - -import static org.assertj.core.api.Assertions.*; -import static org.mockito.Mockito.*; - -import java.util.Iterator; - -import org.junit.Test; - -import com.datastax.driver.core.ResultSet; -import com.datastax.driver.core.Row; - -/** - * Test suite of test cases testing the contract and functionality of the {@link EmptyResultSet}. - * - * @author John Blum - * @see org.springframework.cassandra.core.support.EmptyResultSet - * @since 1.5.0 - */ -public class EmptyResultSetUnitTests { - - @Test - public void nullSafeResultSetReturnsGivenResultSet() { - ResultSet mockResultSet = mock(ResultSet.class); - ResultSet theResultSet = EmptyResultSet.nullSafeResultSet(mockResultSet); - - assertThat(theResultSet).isSameAs(mockResultSet); - } - - @Test - public void nullSAfeResultSetReturnsEmptyResultSetForNull() { - ResultSet resultSet = EmptyResultSet.nullSafeResultSet(null); - - assertThat(resultSet).isInstanceOf(EmptyResultSet.class); - } - - @Test - public void isExhaustedForEmptyResultIsTrue() { - assertThat(EmptyResultSet.nullSafeResultSet(null).isExhausted()).isTrue(); - } - - @Test - public void isFullyFetchedForEmptyResultSetIsTrue() { - assertThat(EmptyResultSet.nullSafeResultSet(null).isFullyFetched()).isTrue(); - } - - @Test - public void getAllExecutionInfoForEmptyResultSetIsEmptyList() { - assertThat(EmptyResultSet.nullSafeResultSet(null).getAllExecutionInfo()).isEmpty(); - } - - @Test(expected = UnsupportedOperationException.class) - public void getColumnDefinitionsForEmptyResultSetThrowsUnsupportedOperationException() { - EmptyResultSet.nullSafeResultSet(null).getColumnDefinitions(); - } - - @Test - public void getExecutionInfoForEmptyResultSetIsNull() { - assertThat(EmptyResultSet.nullSafeResultSet(null).getExecutionInfo()).isNull(); - } - - @Test - public void allForEmptyResultSetIsEmptyList() { - assertThat(EmptyResultSet.nullSafeResultSet(null).all()).isEmpty(); - } - - @Test(expected = UnsupportedOperationException.class) - public void fetchMoreResultsFromEmptyResultSetThrowsUnsupportedOperationException() { - EmptyResultSet.nullSafeResultSet(null).fetchMoreResults(); - } - - @Test - public void iteratorForEmptyResultSetIsEmptyIterator() { - Iterator iterator = EmptyResultSet.nullSafeResultSet(null).iterator(); - - assertThat(iterator).isNotNull(); - assertThat(iterator.hasNext()).isFalse(); - } - - @Test - public void oneForEmptyResultSetIsNull() { - assertThat(EmptyResultSet.nullSafeResultSet(null).one()).isNull(); - } - - @Test(expected = UnsupportedOperationException.class) - public void wasAppliedOnEmptyResultSetThrowsUnsupportedOperationException() { - EmptyResultSet.nullSafeResultSet(null).wasApplied(); - } -} diff --git a/spring-cql/src/test/java/org/springframework/cassandra/core/util/CollectionUtilsUnitTests.java b/spring-cql/src/test/java/org/springframework/cassandra/core/util/CollectionUtilsUnitTests.java deleted file mode 100755 index 61817c713..000000000 --- a/spring-cql/src/test/java/org/springframework/cassandra/core/util/CollectionUtilsUnitTests.java +++ /dev/null @@ -1,138 +0,0 @@ -/* - * 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.cassandra.core.util; - -import static org.assertj.core.api.Assertions.*; - -import java.util.Arrays; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; - -import org.junit.Test; - -/** - * The CollectionUtilsUnitTests class is a test suite of test cases testing the contract and functionality of the - * {@link CollectionUtils} class. - * - * @author John Blum - * @see org.springframework.cassandra.core.util.CollectionUtils - * @since 1.5.0 - */ -public class CollectionUtilsUnitTests { - - List asList(T... array) { - return Arrays.asList(array); - } - - void assertNonNullEmptyArray(Object[] array) { - assertThat(array).isNotNull(); - assertThat(array.length).isEqualTo(0); - } - - void assertNonNullEmptyCollection(Collection collection) { - assertThat(collection).isNotNull(); - assertThat(collection.isEmpty()).isTrue(); - } - - Iterable newIterable(final T... elements) { - return new Iterable() { - @Override - public Iterator iterator() { - return new Iterator() { - int index = 0; - - @Override - public boolean hasNext() { - return (index < elements.length); - } - - @Override - public T next() { - return elements[index++]; - } - }; - } - }; - } - - @Test - public void toArrayWithIterable() { - Object[] array = CollectionUtils.toArray(newIterable(1, 2, 3)); - - assertThat(array).isNotNull(); - assertThat(array.length).isEqualTo(3); - - for (int index = 0; index < array.length; index++) { - Object valueAtIndex = (index + 1); - assertThat(array[index]).isEqualTo(valueAtIndex); - } - } - - @Test - public void toArrayWithEmptyIterable() { - assertNonNullEmptyArray(CollectionUtils.toArray(newIterable())); - } - - @Test - public void toArrayWithNull() { - assertNonNullEmptyArray(CollectionUtils.toArray(null)); - } - - @Test - public void toListWithArray() { - List list = CollectionUtils.toList("test", "testing", "tested"); - - assertThat(list).isNotNull(); - assertThat(list).hasSize(3); - assertThat(list.containsAll(asList("test", "testing", "tested"))).isTrue(); - } - - @Test - public void toListWithEmptyArray() { - assertNonNullEmptyCollection(CollectionUtils.toList()); - } - - @Test - public void toListWithNullArray() { - assertNonNullEmptyCollection(CollectionUtils.toList((Object[]) null)); - } - - @Test - @SuppressWarnings("unchecked") - public void toListWithIterable() { - List list = CollectionUtils.toList(newIterable(1, 2, 3)); - - assertThat(list).isNotNull(); - assertThat(list).hasSize(3); - assertThat(list.containsAll(asList(1, 2, 3))).isTrue(); - } - - @Test - public void toListWithList() { - List expected = asList(1, 2, 3); - List actual = CollectionUtils.toList(expected); - - assertThat(actual).isSameAs(expected); - } - - @Test - public void toListWithNullIterable() { - assertNonNullEmptyCollection(CollectionUtils.toList((Iterable) null)); - } - -} diff --git a/spring-cql/src/test/java/org/springframework/cassandra/test/integration/AbstractEmbeddedCassandraIntegrationTest.java b/spring-cql/src/test/java/org/springframework/cassandra/test/integration/AbstractEmbeddedCassandraIntegrationTest.java index 32bcba044..3942a222e 100755 --- a/spring-cql/src/test/java/org/springframework/cassandra/test/integration/AbstractEmbeddedCassandraIntegrationTest.java +++ b/spring-cql/src/test/java/org/springframework/cassandra/test/integration/AbstractEmbeddedCassandraIntegrationTest.java @@ -19,12 +19,9 @@ import java.util.UUID; import org.junit.ClassRule; import org.junit.Rule; -import org.springframework.cassandra.core.SessionCallback; import org.springframework.cassandra.test.integration.support.CqlDataSet; -import org.springframework.dao.DataAccessException; import com.datastax.driver.core.Cluster; -import com.datastax.driver.core.Session; /** * Abstract base integration test class that starts an embedded Cassandra instance. Test clients can use the @@ -47,12 +44,9 @@ public abstract class AbstractEmbeddedCassandraIntegrationTest { * Initiate a Cassandra environment in test scope. */ @Rule public final CassandraRule cassandraRule = cassandraEnvironment.testInstance() - .before(new SessionCallback() { - @Override - public Object doInSession(Session session) throws DataAccessException { - AbstractEmbeddedCassandraIntegrationTest.this.cluster = session.getCluster(); - return null; - } + .before(session -> { + AbstractEmbeddedCassandraIntegrationTest.this.cluster = session.getCluster(); + return null; }); /** diff --git a/spring-cql/src/test/java/org/springframework/cassandra/test/integration/AbstractKeyspaceCreatingIntegrationTest.java b/spring-cql/src/test/java/org/springframework/cassandra/test/integration/AbstractKeyspaceCreatingIntegrationTest.java index f9bdb30f7..78df44741 100755 --- a/spring-cql/src/test/java/org/springframework/cassandra/test/integration/AbstractKeyspaceCreatingIntegrationTest.java +++ b/spring-cql/src/test/java/org/springframework/cassandra/test/integration/AbstractKeyspaceCreatingIntegrationTest.java @@ -16,8 +16,6 @@ package org.springframework.cassandra.test.integration; import org.junit.ClassRule; -import org.springframework.cassandra.core.SessionCallback; -import org.springframework.dao.DataAccessException; import org.springframework.util.Assert; import com.datastax.driver.core.Session; @@ -68,16 +66,12 @@ public abstract class AbstractKeyspaceCreatingIntegrationTest extends AbstractEm this.keyspace = keyspace; this.session = keyspaceRule.getSession(); - cassandraRule.before(new SessionCallback() { + cassandraRule.before(session -> { - @Override - public Object doInSession(Session session) throws DataAccessException { - - if (!keyspace.equals(session.getLoggedKeyspace())) { - session.execute(String.format("USE %s;", keyspace)); - } - return null; + if (!keyspace.equals(session.getLoggedKeyspace())) { + session.execute(String.format("USE %s;", keyspace)); } + return null; }); } diff --git a/spring-cql/src/test/java/org/springframework/cassandra/test/integration/CassandraRule.java b/spring-cql/src/test/java/org/springframework/cassandra/test/integration/CassandraRule.java index 8bd3a7287..ddc5c6f1b 100644 --- a/spring-cql/src/test/java/org/springframework/cassandra/test/integration/CassandraRule.java +++ b/spring-cql/src/test/java/org/springframework/cassandra/test/integration/CassandraRule.java @@ -28,7 +28,6 @@ import org.springframework.cassandra.core.SessionCallback; import org.springframework.cassandra.test.integration.support.CassandraConnectionProperties; import org.springframework.cassandra.test.integration.support.CqlDataSet; import org.springframework.cassandra.test.integration.support.IntegrationTestNettyOptions; -import org.springframework.dao.DataAccessException; import org.springframework.util.Assert; import org.springframework.util.SocketUtils; @@ -63,11 +62,11 @@ public class CassandraRule extends ExternalResource { private final long startUpTimeout; - private List> before = new ArrayList>(); + private List> before = new ArrayList<>(); - private Map, InvocationMode> invocationModeMap = new HashMap, InvocationMode>(); + private Map, InvocationMode> invocationModeMap = new HashMap<>(); - private List> after = new ArrayList>(); + private List> after = new ArrayList<>(); private Session session; @@ -133,12 +132,9 @@ public class CassandraRule extends ExternalResource { Assert.notNull(cqlDataSet, "CQLDataSet must not be null"); - SessionCallback sessionCallback = new SessionCallback() { - @Override - public Void doInSession(Session session) throws DataAccessException { - load(session, cqlDataSet); - return null; - } + SessionCallback sessionCallback = session -> { + load(session, cqlDataSet); + return null; }; before(invocationMode, sessionCallback); @@ -184,12 +180,9 @@ public class CassandraRule extends ExternalResource { Assert.notNull(cqlDataSet, "CQLDataSet must not be null"); - after.add(new SessionCallback() { - @Override - public Void doInSession(Session session) throws DataAccessException { - load(CassandraRule.this.session, cqlDataSet); - return null; - } + after.add(session -> { + load(CassandraRule.this.session, cqlDataSet); + return null; }); return this; @@ -383,9 +376,7 @@ public class CassandraRule extends ExternalResource { session.execute(String.format("USE %s;", cqlDataSet.getKeyspaceName())); } - for (String statement : cqlDataSet.getCqlStatements()) { - session.execute(statement); - } + cqlDataSet.getCqlStatements().forEach(session::execute); } /** diff --git a/spring-cql/src/test/java/org/springframework/cassandra/test/integration/EmbeddedCassandraServerHelper.java b/spring-cql/src/test/java/org/springframework/cassandra/test/integration/EmbeddedCassandraServerHelper.java index 786403755..6afa77beb 100644 --- a/spring-cql/src/test/java/org/springframework/cassandra/test/integration/EmbeddedCassandraServerHelper.java +++ b/spring-cql/src/test/java/org/springframework/cassandra/test/integration/EmbeddedCassandraServerHelper.java @@ -22,6 +22,7 @@ import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import java.util.Arrays; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @@ -49,8 +50,8 @@ class EmbeddedCassandraServerHelper { public static final long DEFAULT_STARTUP_TIMEOUT_MS = TimeUnit.SECONDS.toMillis(20); public static final String DEFAULT_TMP_DIR = "target/embeddedCassandra"; - private final static AtomicReference sync = new AtomicReference(); - private final static AtomicReference cassandraRef = new AtomicReference(); + private final static AtomicReference sync = new AtomicReference<>(); + private final static AtomicReference cassandraRef = new AtomicReference<>(); private static String launchedYamlFile; @@ -161,12 +162,9 @@ class EmbeddedCassandraServerHelper { final CassandraDaemon cassandraDaemon = new CassandraDaemon(); ExecutorService executor = Executors.newSingleThreadExecutor(); - Future future = executor.submit(new Runnable() { - @Override - public void run() { - cassandraDaemon.activate(); - cassandraRef.compareAndSet(null, cassandraDaemon); - } + Future future = executor.submit(() -> { + cassandraDaemon.activate(); + cassandraRef.compareAndSet(null, cassandraDaemon); }); try { @@ -248,12 +246,6 @@ class EmbeddedCassandraServerHelper { } private static void rmdirs(File... fileOrDirectories) throws IOException { - - for (File fileOrDirectory : fileOrDirectories) { - if (!fileOrDirectory.exists()) { - continue; - } - FileUtils.deleteRecursive(fileOrDirectory); - } + Arrays.stream(fileOrDirectories).filter(File::exists).forEach(FileUtils::deleteRecursive); } } diff --git a/spring-cql/src/test/java/org/springframework/cassandra/test/integration/KeyspaceRule.java b/spring-cql/src/test/java/org/springframework/cassandra/test/integration/KeyspaceRule.java index fd8138df3..f4ab418d2 100644 --- a/spring-cql/src/test/java/org/springframework/cassandra/test/integration/KeyspaceRule.java +++ b/spring-cql/src/test/java/org/springframework/cassandra/test/integration/KeyspaceRule.java @@ -16,9 +16,7 @@ package org.springframework.cassandra.test.integration; import org.junit.rules.ExternalResource; -import org.springframework.cassandra.core.SessionCallback; import org.springframework.cassandra.support.RandomKeySpaceName; -import org.springframework.dao.DataAccessException; import org.springframework.util.Assert; import com.datastax.driver.core.Cluster; @@ -76,12 +74,9 @@ public class KeyspaceRule extends ExternalResource { if (cassandraRule.getCluster() != null) { this.session = cassandraRule.getSession(); } else { - cassandraRule.before(new SessionCallback() { - @Override - public Object doInSession(Session session) throws DataAccessException { - KeyspaceRule.this.session = cassandraRule.getSession(); - return null; - } + cassandraRule.before(session -> { + KeyspaceRule.this.session = cassandraRule.getSession(); + return null; }); } diff --git a/spring-cql/src/test/java/org/springframework/cassandra/test/integration/config/java/KeyspaceCreatingJavaConfig.java b/spring-cql/src/test/java/org/springframework/cassandra/test/integration/config/java/KeyspaceCreatingJavaConfig.java index c4d03ca04..6f801537c 100644 --- a/spring-cql/src/test/java/org/springframework/cassandra/test/integration/config/java/KeyspaceCreatingJavaConfig.java +++ b/spring-cql/src/test/java/org/springframework/cassandra/test/integration/config/java/KeyspaceCreatingJavaConfig.java @@ -40,7 +40,7 @@ public class KeyspaceCreatingJavaConfig extends AbstractTestJavaConfig { @Override protected List getKeyspaceCreations() { - ArrayList list = new ArrayList(); + ArrayList list = new ArrayList<>(); CreateKeyspaceSpecification specification = CreateKeyspaceSpecification.createKeyspace().name(getKeyspaceName()); specification.with(KeyspaceOption.REPLICATION, KeyspaceAttributes.newSimpleReplication(1L)); diff --git a/spring-cql/src/test/java/org/springframework/cassandra/test/integration/support/CassandraConnectionProperties.java b/spring-cql/src/test/java/org/springframework/cassandra/test/integration/support/CassandraConnectionProperties.java index 0dc9a28f1..104833a3e 100644 --- a/spring-cql/src/test/java/org/springframework/cassandra/test/integration/support/CassandraConnectionProperties.java +++ b/spring-cql/src/test/java/org/springframework/cassandra/test/integration/support/CassandraConnectionProperties.java @@ -125,11 +125,7 @@ public class CassandraConnectionProperties extends Properties { * @return the property value */ public int getInt(String propertyName) { - return convert(propertyName, Integer.class, new Converter() { - public Integer convert(String value) { - return Integer.parseInt(value); - } - }); + return convert(propertyName, Integer.class, Integer::parseInt); } /** @@ -139,11 +135,7 @@ public class CassandraConnectionProperties extends Properties { * @return the property value */ public long getLong(String propertyName) { - return convert(propertyName, Long.class, new Converter() { - public Long convert(String value) { - return Long.parseLong(value); - } - }); + return convert(propertyName, Long.class, Long::parseLong); } /** @@ -153,11 +145,7 @@ public class CassandraConnectionProperties extends Properties { * @return the property value */ public boolean getBoolean(String propertyName) { - return convert(propertyName, Boolean.class, new Converter() { - public Boolean convert(String value) { - return Boolean.parseBoolean(value); - } - }); + return convert(propertyName, Boolean.class, Boolean::parseBoolean); } private T convert(String propertyName, Class type, Converter converter) { diff --git a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/Constants.java b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/Constants.java deleted file mode 100644 index 963c16de3..000000000 --- a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/Constants.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright 2013-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. - * 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.cassandra; - -/** - * @author David Webb - */ -public interface Constants { - -} diff --git a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/config/BeanDefinitionBuilderArgument.java b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/config/BeanDefinitionBuilderArgument.java index 30ff8a763..041c44c84 100644 --- a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/config/BeanDefinitionBuilderArgument.java +++ b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/config/BeanDefinitionBuilderArgument.java @@ -1,12 +1,12 @@ /* - * Copyright 2013-2014 the original author or authors - * + * Copyright 2013-2017 the original author or authors + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. @@ -28,16 +28,16 @@ import org.springframework.util.StringUtils; *

* Easy and succinct to create if methods {@link #ref(CharSequence)} or {@link #val(Object)} are used and imported * statically. - * + * * @see BeanDefinitionBuilderArgument#ref(CharSequence) * @see BeanDefinitionBuilderArgument#val(Object) */ public class BeanDefinitionBuilderArgument { /** - * Returns a {@link BeanDefinitionBuilderArgument} with {@link #reference} equal to true. Convenient if + * Returns a {@link BeanDefinitionBuilderArgument} with {@link #reference} equal to {@code true}. Convenient if * imported statically. - * + * * @param value The name of the bean reference. */ public static BeanDefinitionBuilderArgument ref(CharSequence value) { @@ -45,9 +45,9 @@ public class BeanDefinitionBuilderArgument { } /** - * Returns a {@link BeanDefinitionBuilderArgument} with {@link #reference} equal to false. Convenient if + * Returns a {@link BeanDefinitionBuilderArgument} with {@link #reference} equal to {@code false}. Convenient if * imported statically. - * + * * @param value The constructor argument's value. */ public static BeanDefinitionBuilderArgument val(Object value) { diff --git a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/config/BeanDefinitionUtils.java b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/config/BeanDefinitionUtils.java index 76a7a21ef..f562f6794 100644 --- a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/config/BeanDefinitionUtils.java +++ b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/config/BeanDefinitionUtils.java @@ -1,12 +1,12 @@ /* - * Copyright 2013-2016 the original author or authors - * + * Copyright 2013-2017 the original author or authors + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. @@ -39,15 +39,15 @@ public class BeanDefinitionUtils { /** * Returns a {@link BeanDefinitionBuilder} iff no {@link BeanDefinition} of the required type is found in the given - * {@link ListableBeanFactory}, otherwise returns null, indicating that at least one existed. - * + * {@link ListableBeanFactory}, otherwise returns {@code null}, indicating that at least one existed. + * * @param factory The {@link ListableBeanFactory} in which to look for the {@link BeanDefinition}, including * ancestors. * @param requiredType The {@link BeanDefinition}'s required type. * @param instantiableType The instantiable type for the {@link BeanDefinitionBuilder}. * @param constructorArgs Any {@link BeanDefinitionBuilderArgument}s required by the instantiableType's constructor. * @return A {@link BeanDefinitionBuilder} iff no {@link BeanDefinition} of the required type is found, otherwise - * null. + * {@code null}. * @see BeanDefinitionUtils#createBeanDefinitionBuilderIfNoBeanDefinitionOfTypeExists(ListableBeanFactory, Class, * Class, BeanDefinitionBuilderArgument...) * @see BeanDefinitionBuilderArgument#ref(Object) @@ -80,17 +80,15 @@ public class BeanDefinitionUtils { /** * Returns the single {@link BeanDefinitionHolder} with the given type, or null of none were found and - * required was false, otherwise throws {@link IllegalArgumentException}. - * - * @param registry The {@link BeanDefinitionRegistry}, often the very same instance as the factor - * parameter. - * @param factory The {@link ListableBeanFactory}, often the very same instance as the registry - * parameter. + * {@code required} was false, otherwise throws {@link IllegalArgumentException}. + * + * @param registry The {@link BeanDefinitionRegistry}, often the very same instance as the {@code factor} parameter. + * @param factory The {@link ListableBeanFactory}, often the very same instance as the {@code registry} parameter. * @param type The required {@link BeanDefinition}'s type. - * @param includeNonSingletons Whether to include beans with scope other than singleton + * @param includeNonSingletons Whether to include beans with scope other than {@code singleton} * @param allowEagerInit Whether to allow eager initialization of beans. * @param required Whether to allow the return of null if none were found. - * @return The {@link BeanDefinitionHolder} or null if none found, depending on the value of required. + * @return The {@link BeanDefinitionHolder} or null if none found, depending on the value of {@code required}. * @throws IllegalArgumentException If multiple were found. * @see BeanFactoryUtils#beanNamesForTypeIncludingAncestors(ListableBeanFactory, Class, boolean, boolean) */ @@ -119,13 +117,11 @@ public class BeanDefinitionUtils { /** * Returns all {@link BeanDefinitionHolder}s with the given type. - * - * @param registry The {@link BeanDefinitionRegistry}, often the very same instance as the factor - * parameter. - * @param factory The {@link ListableBeanFactory}, often the very same instance as the registry - * parameter. + * + * @param registry The {@link BeanDefinitionRegistry}, often the very same instance as the {@code factor} parameter. + * @param factory The {@link ListableBeanFactory}, often the very same instance as the {@code registry} parameter. * @param type The required {@link BeanDefinition}'s type. - * @param includeNonSingletons Whether to include beans with scope other than singleton + * @param includeNonSingletons Whether to include beans with scope other than {@code singleton} * @param allowEagerInit Whether to allow eager initialization of beans. * @param required Whether to allow the return of null if none were found. * @return The {@link BeanDefinitionHolder}s -- never returns null. diff --git a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/config/CassandraEntityClassScanner.java b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/config/CassandraEntityClassScanner.java index 591952377..817ddc1a5 100644 --- a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/config/CassandraEntityClassScanner.java +++ b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/config/CassandraEntityClassScanner.java @@ -1,12 +1,12 @@ /* - * Copyright 2013-2014 the original author or authors - * + * Copyright 2013-2017 the original author or authors + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. @@ -33,7 +33,7 @@ import org.springframework.util.StringUtils; /** * Scans packages for Cassandra entities. - * + * * @author Matthew T. Adams */ public class CassandraEntityClassScanner { @@ -55,8 +55,8 @@ public class CassandraEntityClassScanner { return new CassandraEntityClassScanner(entityBasePackages, entityBasePackageClasses).scanForEntityClasses(); } - protected Set entityBasePackages = new HashSet(); - protected Set> entityBasePackageClasses = new HashSet>(); + protected Set entityBasePackages = new HashSet<>(); + protected Set> entityBasePackageClasses = new HashSet<>(); protected ClassLoader beanClassLoader; public CassandraEntityClassScanner() {} @@ -85,7 +85,7 @@ public class CassandraEntityClassScanner { } public void setEntityBasePackages(Collection entityBasePackages) { - this.entityBasePackages = entityBasePackages == null ? new HashSet() : new HashSet( + this.entityBasePackages = entityBasePackages == null ? new HashSet<>() : new HashSet<>( entityBasePackages); } @@ -94,7 +94,7 @@ public class CassandraEntityClassScanner { } public void setEntityBasePackageClasses(Collection> entityBasePackageClasses) { - this.entityBasePackageClasses = entityBasePackageClasses == null ? new HashSet>() : new HashSet>( + this.entityBasePackageClasses = entityBasePackageClasses == null ? new HashSet<>() : new HashSet<>( entityBasePackageClasses); } @@ -104,14 +104,14 @@ public class CassandraEntityClassScanner { /** * Scans the mapping base package for entity classes annotated with {@link Table} or {@link Persistent}. - * + * * @see #getEntityBasePackages() - * @return Set<Class<?>> representing the annotated entity classes found. + * @return {@code Set>} representing the annotated entity classes found. * @throws ClassNotFoundException */ public Set> scanForEntityClasses() throws ClassNotFoundException { - Set> classes = new HashSet>(); + Set> classes = new HashSet<>(); for (String basePackage : getEntityBasePackages()) { classes.addAll(scanBasePackageForEntities(basePackage)); @@ -126,7 +126,7 @@ public class CassandraEntityClassScanner { protected Set> scanBasePackageForEntities(String basePackage) throws ClassNotFoundException { - HashSet> classes = new HashSet>(); + HashSet> classes = new HashSet<>(); if (StringUtils.hasText(basePackage)) { ClassPathScanningCandidateComponentProvider componentProvider = new ClassPathScanningCandidateComponentProvider( diff --git a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/config/DefaultBeanNames.java b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/config/DefaultBeanNames.java index 09e8050f2..230837ef6 100644 --- a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/config/DefaultBeanNames.java +++ b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/config/DefaultBeanNames.java @@ -1,12 +1,12 @@ /* * 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. @@ -26,4 +26,5 @@ public interface DefaultBeanNames extends DefaultCqlBeanNames { String DATA_TEMPLATE = "cassandraTemplate"; String CONVERTER = "cassandraConverter"; String CONTEXT = "cassandraMapping"; + String USER_TYPE_RESOLVER = "userTypeResolver"; } diff --git a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/config/SchemaAction.java b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/config/SchemaAction.java index 5305b2d22..68ad1ea05 100644 --- a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/config/SchemaAction.java +++ b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/config/SchemaAction.java @@ -1,12 +1,12 @@ /* - * Copyright 2013-2014 the original author or authors - * + * Copyright 2013-2017 the original author or authors + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. @@ -18,7 +18,7 @@ package org.springframework.data.cassandra.config; /** * Enum identifying any schema actions to take at startup. - * + * * @author Matthew T. Adams * @author John Blum */ @@ -47,7 +47,7 @@ public enum SchemaAction { /** * Drop all tables in the keyspace, then create each table as necessary. */ - RECREATE_DROP_UNUSED; + RECREATE_DROP_UNUSED // TODO: // /** diff --git a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/config/xml/CassandraMappingContextParser.java b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/config/xml/CassandraMappingContextParser.java index f71359849..2e665457e 100644 --- a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/config/xml/CassandraMappingContextParser.java +++ b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/config/xml/CassandraMappingContextParser.java @@ -95,16 +95,16 @@ public class CassandraMappingContextParser extends AbstractSingleBeanDefinitionP } } - Set mappings = new HashSet(); + Set mappings = new HashSet<>(); - for (Element entity : DomUtils.getChildElementsByTagName(element, "entity")) { + DomUtils.getChildElementsByTagName(element, "entity").forEach(entity -> { EntityMapping entityMapping = parseEntity(entity); if (entityMapping != null) { mappings.add(entityMapping); } - } + }); List userTypeResolvers = DomUtils.getChildElementsByTagName(element, "user-type-resolver"); String userTypeResolverRef = element.getAttribute("user-type-resolver-ref"); @@ -169,7 +169,7 @@ public class CassandraMappingContextParser extends AbstractSingleBeanDefinitionP protected Map parsePropertyMappings(Element entity) { - Map propertyMappings = new HashMap(); + Map propertyMappings = new HashMap<>(); for (Element property : DomUtils.getChildElementsByTagName(entity, "property")) { diff --git a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/convert/CassandraConverters.java b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/convert/CassandraConverters.java index 8d7f96055..c72f571ec 100644 --- a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/convert/CassandraConverters.java +++ b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/convert/CassandraConverters.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2016-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,7 +52,7 @@ abstract class CassandraConverters { */ public static Collection getConvertersToRegister() { - List converters = new ArrayList(); + List converters = new ArrayList<>(); converters.add(RowToCassandraLocalDateConverter.INSTANCE); converters.add(RowToBooleanConverter.INSTANCE); @@ -130,7 +130,7 @@ abstract class CassandraConverters { public Converter getConverter(Class targetType) { Assert.notNull(targetType, "Target type must not be null"); - return new RowToNumber(targetType); + return new RowToNumber<>(targetType); } private static final class RowToNumber implements Converter { diff --git a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/convert/CassandraJodaTimeConverters.java b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/convert/CassandraJodaTimeConverters.java index 4d672f2f0..dd946ba79 100644 --- a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/convert/CassandraJodaTimeConverters.java +++ b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/convert/CassandraJodaTimeConverters.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2016-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,7 +50,7 @@ public abstract class CassandraJodaTimeConverters { return Collections.emptySet(); } - List> converters = new ArrayList>(); + List> converters = new ArrayList<>(); converters.add(CassandraLocalDateToLocalDateConverter.INSTANCE); converters.add(LocalDateToCassandraLocalDateConverter.INSTANCE); diff --git a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/convert/CassandraJsr310Converters.java b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/convert/CassandraJsr310Converters.java index 05fafa848..a1dc6fe37 100644 --- a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/convert/CassandraJsr310Converters.java +++ b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/convert/CassandraJsr310Converters.java @@ -51,7 +51,7 @@ public abstract class CassandraJsr310Converters { return Collections.emptySet(); } - List> converters = new ArrayList>(); + List> converters = new ArrayList<>(); converters.add(CassandraLocalDateToLocalDateConverter.INSTANCE); converters.add(LocalDateToCassandraLocalDateConverter.INSTANCE); diff --git a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/convert/CassandraThreeTenBackPortConverters.java b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/convert/CassandraThreeTenBackPortConverters.java index d260c6892..22de117ea 100644 --- a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/convert/CassandraThreeTenBackPortConverters.java +++ b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/convert/CassandraThreeTenBackPortConverters.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2016-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,7 +52,7 @@ public abstract class CassandraThreeTenBackPortConverters { return Collections.emptySet(); } - List> converters = new ArrayList>(); + List> converters = new ArrayList<>(); converters.add(CassandraLocalDateToLocalDateConverter.INSTANCE); converters.add(LocalDateToCassandraLocalDateConverter.INSTANCE); diff --git a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/convert/CustomConversions.java b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/convert/CustomConversions.java index 7fb2606bb..dd730bc37 100644 --- a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/convert/CustomConversions.java +++ b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/convert/CustomConversions.java @@ -89,7 +89,7 @@ public class CustomConversions { this.customWriteTargetTypes = new ConcurrentHashMap<>(); this.rawWriteTargetTypes = new ConcurrentHashMap<>(); - List toRegister = new ArrayList(); + List toRegister = new ArrayList<>(); // Add user provided converters to make sure they can override the defaults toRegister.addAll(converters); @@ -103,9 +103,7 @@ public class CustomConversions { toRegister.addAll(Jsr310Converters.getConvertersToRegister()); toRegister.addAll(ThreeTenBackPortConverters.getConvertersToRegister()); - for (Object converter : toRegister) { - registerConversion(converter); - } + toRegister.forEach(this::registerConversion); Collections.reverse(toRegister); diff --git a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/convert/MappingCassandraConverter.java b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/convert/MappingCassandraConverter.java index aabb5b982..00f18cac8 100644 --- a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/convert/MappingCassandraConverter.java +++ b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/convert/MappingCassandraConverter.java @@ -254,7 +254,8 @@ public class MappingCassandraConverter extends AbstractCassandraConverter PropertyValueProvider propertyProvider) { return instantiators.getInstantiatorFor(entity).createInstance(entity, - new PersistentEntityParameterValueProvider<>(entity, propertyProvider, Optional.empty())); + new PersistentEntityParameterValueProvider<>(entity, propertyProvider, + Optional.empty())); } /* (non-Javadoc) @@ -681,9 +682,9 @@ public class MappingCassandraConverter extends AbstractCassandraConverter Collection original = (Collection) value; Collection converted = CollectionFactory.createCollection(getCollectionType(type), original.size()); - for (Object element : original) { - converted.add(convertToCassandraColumn(Optional.ofNullable(element), actualType).orElse(null)); - } + original.stream() // + .map(element -> convertToCassandraColumn(Optional.ofNullable(element), actualType).orElse(null)) + .forEach(converted::add); return Optional.of((O) converted); } diff --git a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/core/CassandraAdminOperations.java b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/core/CassandraAdminOperations.java index cbc70300e..728cd4aaa 100644 --- a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/core/CassandraAdminOperations.java +++ b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/core/CassandraAdminOperations.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2016 the original author or authors. + * Copyright 2013-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,9 +35,8 @@ public interface CassandraAdminOperations extends CassandraOperations { /** * Create a table with the name given and fields corresponding to the given class. If the table already exists and - * parameter ifNotExists is {@literal true}, this is a no-op and {@literal false} is returned. If the - * table doesn't exist, parameter ifNotExists is ignored, the table is created and {@literal true} is - * returned. + * parameter {@code ifNotExists} is {@literal true}, this is a no-op and {@literal false} is returned. If the table + * doesn't exist, parameter {@code ifNotExists} is ignored, the table is created and {@literal true} is returned. * * @param ifNotExists If true, will only create the table if it doesn't exist, else the create operation will be * ignored and the method will return {@literal false}. diff --git a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/core/CassandraTemplate.java b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/core/CassandraTemplate.java index 11ab09f02..d7696bd04 100644 --- a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/core/CassandraTemplate.java +++ b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/core/CassandraTemplate.java @@ -15,6 +15,8 @@ */ package org.springframework.data.cassandra.core; +import java.util.ArrayList; +import java.util.Collection; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; @@ -305,7 +307,7 @@ public class CassandraTemplate implements CassandraOperations { Select select = QueryBuilder.select().all().from(entity.getTableName().toCql()); - select.where(QueryBuilder.in(idProperty.getColumnName().toCql(), CollectionUtils.toArray(ids))); + select.where(QueryBuilder.in(idProperty.getColumnName().toCql(), toList(ids))); return select(select, entityClass); } @@ -456,6 +458,19 @@ public class CassandraTemplate implements CassandraOperations { return new CassandraBatchTemplate(this); } + private List toList(Iterable iterable) { + + if (iterable instanceof List) { + return (List) iterable; + } + + if (iterable instanceof Collection) { + return new ArrayList<>((Collection) iterable); + } + + return StreamSupport.stream(iterable.spliterator(), false).collect(Collectors.toList()); + } + private static class StatementCallback implements SessionCallback, CqlProvider { private final Statement statement; diff --git a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/core/CassandraValue.java b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/core/CassandraValue.java index 8ef28fb97..450d133a7 100644 --- a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/core/CassandraValue.java +++ b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/core/CassandraValue.java @@ -1,12 +1,12 @@ /* * Copyright 2013-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. * 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. @@ -21,9 +21,11 @@ import com.datastax.driver.core.DataType; /** * Simple Cassandra value of the ByteBuffer with DataType - * + * * @author Alex Shvid + * @deprecated as of 2.0, not used anymore. */ +@Deprecated public class CassandraValue { private final ByteBuffer value; diff --git a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/core/DeletionListener.java b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/core/DeletionListener.java index a09175ce3..8c9097218 100644 --- a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/core/DeletionListener.java +++ b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/core/DeletionListener.java @@ -4,6 +4,14 @@ import java.util.Collection; import com.datastax.driver.core.ResultSet; +/** + * Listener for asynchronous repository insert or update methods. + * + * @author Matthew T. Adams + * @author Mark Paluch + * @deprecated as of 2.0, not used anymore. + */ +@Deprecated public interface DeletionListener { void onDeletionComplete(Collection entities); diff --git a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/core/WriteListener.java b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/core/WriteListener.java index a0a27079a..a1a03404c 100644 --- a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/core/WriteListener.java +++ b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/core/WriteListener.java @@ -1,12 +1,12 @@ /* * Copyright 2013-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. * 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. @@ -21,14 +21,16 @@ import com.datastax.driver.core.ResultSet; /** * Listener for asynchronous repository insert or update methods. - * + * * @author Matthew T. Adams + * @deprecated as of 2.0, not used anymore. */ +@Deprecated public interface WriteListener { /** * Called upon completion of the asynchronous insert or update. - * + * * @param entities The entities inserted or updated. */ void onWriteComplete(Collection entities); diff --git a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/mapping/BasicCassandraMappingContext.java b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/mapping/BasicCassandraMappingContext.java index 48d62048f..c1cedad8b 100644 --- a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/mapping/BasicCassandraMappingContext.java +++ b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/mapping/BasicCassandraMappingContext.java @@ -267,10 +267,10 @@ public class BasicCassandraMappingContext CassandraPersistentEntity entity; if (userDefinedType != null) { - entity = new CassandraUserTypePersistentEntity(typeInformation, this, verifier, userTypeResolver); + entity = new CassandraUserTypePersistentEntity<>(typeInformation, this, verifier, userTypeResolver); userDefinedTypes.add(entity); } else { - entity = new BasicCassandraPersistentEntity(typeInformation, this, verifier); + entity = new BasicCassandraPersistentEntity<>(typeInformation, this, verifier); } if (context != null) { @@ -344,14 +344,7 @@ public class BasicCassandraMappingContext } private boolean hasMappedUserType(CqlIdentifier identifier) { - - for (CassandraPersistentEntity userDefinedType : userDefinedTypes) { - if (userDefinedType.getTableName().equals(identifier)) { - return true; - } - } - - return false; + return userDefinedTypes.stream().map(CassandraPersistentEntity::getTableName).anyMatch(identifier::equals); } /* (non-Javadoc) @@ -410,16 +403,12 @@ public class BasicCassandraMappingContext final CreateUserTypeSpecification specification = CreateUserTypeSpecification.createType(entity.getTableName()); - entity.doWithProperties(new PropertyHandler() { + entity.doWithProperties((PropertyHandler) property -> { - @Override - public void doWithPersistentProperty(final CassandraPersistentProperty property) { - - // Use frozen literal to not resolve types from Cassandra. - // At this stage, they might be not created yet. - specification.field(property.getColumnName(), - getDataTypeWithUserTypeFactory(property, DataTypeProvider.FrozenLiteral)); - } + // Use frozen literal to not resolve types from Cassandra. + // At this stage, they might be not created yet. + specification.field(property.getColumnName(), + getDataTypeWithUserTypeFactory(property, DataTypeProvider.FrozenLiteral)); }); if (specification.getFields().isEmpty()) { diff --git a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/mapping/BasicCassandraPersistentEntity.java b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/mapping/BasicCassandraPersistentEntity.java index ec6d00b2b..26c6b3bdb 100644 --- a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/mapping/BasicCassandraPersistentEntity.java +++ b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/mapping/BasicCassandraPersistentEntity.java @@ -144,7 +144,7 @@ public class BasicCassandraPersistentEntity extends BasicPersistentEntity getCompositePrimaryKeyProperties() { - List properties = new ArrayList(); + List properties = new ArrayList<>(); Assert.state(isCompositePrimaryKey(), String.format("[%s] does not represent a composite primary key class", this.getType().getName())); diff --git a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/mapping/BasicCassandraPersistentProperty.java b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/mapping/BasicCassandraPersistentProperty.java index 589799436..0fff9ac6f 100644 --- a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/mapping/BasicCassandraPersistentProperty.java +++ b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/mapping/BasicCassandraPersistentProperty.java @@ -23,6 +23,7 @@ import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; +import java.util.stream.Collectors; import org.springframework.cassandra.core.Ordering; import org.springframework.cassandra.core.PrimaryKeyType; @@ -374,7 +375,7 @@ public class BasicCassandraPersistentProperty extends AnnotationBasedPersistentP protected List determineColumnNames() { - List columnNames = new ArrayList(); + List columnNames = new ArrayList<>(); if (isCompositePrimaryKey()) { // then the id type has @PrimaryKeyClass addCompositePrimaryKeyColumnNames(getCompositePrimaryKeyEntity(), columnNames); @@ -458,7 +459,7 @@ public class BasicCassandraPersistentProperty extends AnnotationBasedPersistentP columnNames.size())); this.columnNames = this.explicitColumnNames = Collections - .unmodifiableList(new ArrayList(columnNames)); + .unmodifiableList(new ArrayList<>(columnNames)); } /* (non-Javadoc) @@ -473,12 +474,11 @@ public class BasicCassandraPersistentProperty extends AnnotationBasedPersistentP this.forceQuote = forceQuote; } - List columnNames = new ArrayList( - this.columnNames == null ? 0 : this.columnNames.size()); - - for (CqlIdentifier columnName : getColumnNames()) { - columnNames.add(cqlId(columnName.getUnquoted(), forceQuote)); - } + List columnNames = getColumnNames() // + .stream() // + .map(CqlIdentifier::getUnquoted) // + .map(name -> cqlId(name, forceQuote)) // + .collect(Collectors.toList()); setColumnNames(columnNames); } @@ -521,7 +521,7 @@ public class BasicCassandraPersistentProperty extends AnnotationBasedPersistentP */ @Override protected Association createAssociation() { - return new Association(this, null); + return new Association<>(this, null); } /* (non-Javadoc) diff --git a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/mapping/CassandraPersistentProperty.java b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/mapping/CassandraPersistentProperty.java index f566f57e7..dc96a4d7a 100644 --- a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/mapping/CassandraPersistentProperty.java +++ b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/mapping/CassandraPersistentProperty.java @@ -135,7 +135,7 @@ public interface CassandraPersistentProperty /** * Sets this property's column names to the collection given. The given collection must have the same size as this - * property's current list of column names, and must contain no null elements. + * property's current list of column names, and must contain no {@code null} elements. * * @param columnName */ diff --git a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/mapping/CassandraSimpleTypeHolder.java b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/mapping/CassandraSimpleTypeHolder.java index 262769c8a..d5eef01a9 100644 --- a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/mapping/CassandraSimpleTypeHolder.java +++ b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/mapping/CassandraSimpleTypeHolder.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2016 the original author or authors + * Copyright 2013-2017 the original author or authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,10 +17,10 @@ package org.springframework.data.cassandra.mapping; import java.util.Collections; import java.util.HashMap; -import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; +import java.util.stream.Collectors; import org.springframework.dao.InvalidDataAccessApiUsageException; import org.springframework.data.mapping.model.SimpleTypeHolder; @@ -30,7 +30,9 @@ import com.datastax.driver.core.CodecRegistry; import com.datastax.driver.core.DataType; import com.datastax.driver.core.DataType.Name; import com.datastax.driver.core.Row; +import com.datastax.driver.core.TypeCodec; import com.datastax.driver.core.UDTValue; +import com.google.common.reflect.TypeToken; /** * Simple constant holder for a {@link SimpleTypeHolder} enriched with Cassandra specific simple types. @@ -51,7 +53,7 @@ public class CassandraSimpleTypeHolder extends SimpleTypeHolder { CodecRegistry codecRegistry = CodecRegistry.DEFAULT_INSTANCE; - Map, Class> primitiveWrappers = new HashMap, Class>(8); + Map, Class> primitiveWrappers = new HashMap<>(8); primitiveWrappers.put(Boolean.class, boolean.class); primitiveWrappers.put(Byte.class, byte.class); primitiveWrappers.put(Character.class, char.class); @@ -78,7 +80,7 @@ public class CassandraSimpleTypeHolder extends SimpleTypeHolder { */ private static Map nameToDataType() { - Map nameToDataType = new HashMap(16); + Map nameToDataType = new HashMap<>(16); for (DataType dataType : DataType.allPrimitiveTypes()) { nameToDataType.put(dataType.getName(), dataType); @@ -95,7 +97,7 @@ public class CassandraSimpleTypeHolder extends SimpleTypeHolder { private static Map, DataType> classToDataType(Map, Class> primitiveWrappers, CodecRegistry codecRegistry) { - Map, DataType> classToDataType = new HashMap, DataType>(16); + Map, DataType> classToDataType = new HashMap<>(16); for (DataType dataType : DataType.allPrimitiveTypes()) { @@ -128,13 +130,11 @@ public class CassandraSimpleTypeHolder extends SimpleTypeHolder { */ private static Set> getCassandraPrimitiveTypes(CodecRegistry codecRegistry) { - Set> simpleTypes = new HashSet>(); - for (DataType dataType : DataType.allPrimitiveTypes()) { - - Class javaClass = codecRegistry.codecFor(dataType).getJavaType().getRawType(); - simpleTypes.add(javaClass); - } - return simpleTypes; + return DataType.allPrimitiveTypes().stream() // + .map(codecRegistry::codecFor) // + .map(TypeCodec::getJavaType) // + .map(TypeToken::getRawType) // + .collect(Collectors.toSet()); } /** diff --git a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/mapping/EntityMapping.java b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/mapping/EntityMapping.java index 582143a12..d881ad3db 100644 --- a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/mapping/EntityMapping.java +++ b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/mapping/EntityMapping.java @@ -85,8 +85,8 @@ public class EntityMapping { } public void setPropertyMappings(Map propertyMappings) { - this.propertyMappings = (propertyMappings != null ? new HashMap(propertyMappings) - : Collections. emptyMap()); + this.propertyMappings = (propertyMappings != null ? new HashMap<>(propertyMappings) + : Collections.emptyMap()); } public String getTableName() { diff --git a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/mapping/Mapping.java b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/mapping/Mapping.java index 461c3305f..9eab0b751 100644 --- a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/mapping/Mapping.java +++ b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/mapping/Mapping.java @@ -1,12 +1,12 @@ /* * Copyright 2013-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. * 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. @@ -21,7 +21,7 @@ import java.util.Set; public class Mapping { - private Set entityMappings = new HashSet(); + private Set entityMappings = new HashSet<>(); public Set getEntityMappings() { return Collections.unmodifiableSet(entityMappings); @@ -34,6 +34,6 @@ public class Mapping { return; } - this.entityMappings = new HashSet(mappings); + this.entityMappings = new HashSet<>(mappings); } } diff --git a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/mapping/PrimaryKey.java b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/mapping/PrimaryKey.java index a48d9f8a2..425cd05f6 100644 --- a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/mapping/PrimaryKey.java +++ b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/mapping/PrimaryKey.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2014 the original author or authors + * Copyright 2013-2017 the original author or authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,8 +24,8 @@ import org.springframework.data.annotation.Id; /** * Identifies the primary key field of the entity, which may be of a basic type or of a type that represents a composite - * primary key class. This field corresponds to the PRIMARY KEY of the corresponding Cassandra table. Only - * one field in a given type hierarchy may be annotated with this annotation. + * primary key class. This field corresponds to the {@code PRIMARY KEY} of the corresponding Cassandra table. Only one + * field in a given type hierarchy may be annotated with this annotation. *

* Remember, if the Cassandra table has multiple primary key columns, then you must define a class annotated with * {@link PrimaryKeyClass} to represent the primary key! diff --git a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/mapping/PrimaryKeyClassEntityMetadataVerifier.java b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/mapping/PrimaryKeyClassEntityMetadataVerifier.java index 41a9dc7e3..f87e7efbe 100644 --- a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/mapping/PrimaryKeyClassEntityMetadataVerifier.java +++ b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/mapping/PrimaryKeyClassEntityMetadataVerifier.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2016-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,12 +42,12 @@ public class PrimaryKeyClassEntityMetadataVerifier implements CassandraPersisten return; } - List exceptions = new ArrayList(); + List exceptions = new ArrayList<>(); - final List idProperties = new ArrayList(); - final List compositePrimaryKeys = new ArrayList(); - final List partitionKeyColumns = new ArrayList(); - final List primaryKeyColumns = new ArrayList(); + List idProperties = new ArrayList<>(); + List compositePrimaryKeys = new ArrayList<>(); + List partitionKeyColumns = new ArrayList<>(); + List primaryKeyColumns = new ArrayList<>(); Class entityType = entity.getType(); diff --git a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/mapping/VerifierMappingExceptions.java b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/mapping/VerifierMappingExceptions.java index e9a80e4bc..56e74f2c1 100644 --- a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/mapping/VerifierMappingExceptions.java +++ b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/mapping/VerifierMappingExceptions.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2016 the original author or authors + * Copyright 2013-2017 the original author or authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,6 +18,7 @@ package org.springframework.data.cassandra.mapping; import java.util.Collection; import java.util.Collections; import java.util.LinkedList; +import java.util.stream.Collectors; import org.springframework.data.mapping.model.MappingException; import org.springframework.util.Assert; @@ -49,7 +50,7 @@ public class VerifierMappingExceptions extends MappingException { Assert.notNull(entity, "CassandraPersistentEntity must not be null"); - this.exceptions = Collections.unmodifiableCollection(new LinkedList(exceptions)); + this.exceptions = Collections.unmodifiableCollection(new LinkedList<>(exceptions)); this.className = entity.getType().getName(); } @@ -65,7 +66,7 @@ public class VerifierMappingExceptions extends MappingException { Assert.notNull(entity, "CassandraPersistentEntity must not be null"); - this.exceptions = new LinkedList(); + this.exceptions = new LinkedList<>(); this.className = entity.getType().getName(); } @@ -96,13 +97,7 @@ public class VerifierMappingExceptions extends MappingException { * @return The Collection of Messages */ public Collection getMessages() { - Collection messages = new LinkedList(); - - for (MappingException e : exceptions) { - messages.add(e.getMessage()); - } - - return messages; + return exceptions.stream().map(Throwable::getMessage).collect(Collectors.toList()); } /** diff --git a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/repository/MapId.java b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/repository/MapId.java index d323ee092..188ff0488 100644 --- a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/repository/MapId.java +++ b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/repository/MapId.java @@ -1,3 +1,18 @@ +/* + * 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.cassandra.repository; import java.io.Serializable; @@ -6,17 +21,17 @@ import java.util.Map; /** * Interface that represents the id of a persistent entity, where the keys correspond to the entity's JavaBean * properties. - * + * * @author Matthew T. Adams */ public interface MapId extends Serializable, Map { /** - * Builder method that adds the value for the named property, then returns this. - * + * Builder method that adds the value for the named property, then returns {@code this}. + * * @param name The property name containing the value. * @param value The property value. - * @return this + * @return {@code this} */ MapId with(String name, Serializable value); } diff --git a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/repository/cdi/CassandraRepositoryExtension.java b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/repository/cdi/CassandraRepositoryExtension.java index fa6c1812d..b0f637445 100644 --- a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/repository/cdi/CassandraRepositoryExtension.java +++ b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/repository/cdi/CassandraRepositoryExtension.java @@ -35,12 +35,12 @@ import org.springframework.data.repository.cdi.CdiRepositoryExtensionSupport; /** * A portable CDI extension which registers beans for Spring Data Cassandra repositories. - * + * * @author Mark Paluch */ public class CassandraRepositoryExtension extends CdiRepositoryExtensionSupport { - private final Map, Bean> cassandraOperationsMap = new HashMap, Bean>(); + private final Map, Bean> cassandraOperationsMap = new HashMap<>(); /** * Implementation of a an observer which checks for CassandraOperations beans and stores them in @@ -52,11 +52,9 @@ public class CassandraRepositoryExtension extends CdiRepositoryExtensionSupport @SuppressWarnings("unchecked") void processBean(@Observes ProcessBean processBean) { Bean bean = processBean.getBean(); - for (Type type : bean.getTypes()) { - if (type instanceof Class && CassandraOperations.class.isAssignableFrom((Class) type)) { - cassandraOperationsMap.put(bean.getQualifiers(), ((Bean) bean)); - } - } + bean.getTypes().stream() // + .filter(type -> type instanceof Class && CassandraOperations.class.isAssignableFrom((Class) type)) // + .forEach(type -> cassandraOperationsMap.put(bean.getQualifiers(), ((Bean) bean))); } /** @@ -94,7 +92,7 @@ public class CassandraRepositoryExtension extends CdiRepositoryExtensionSupport Bean cassandraOperationsBean = Optional.ofNullable(this.cassandraOperationsMap.get(qualifiers)).orElseThrow(() -> new UnsatisfiedResolutionException(String.format("Unable to resolve a bean for '%s' with qualifiers %s.", CassandraOperations.class.getName(), qualifiers))); - return new CassandraRepositoryBean(cassandraOperationsBean, qualifiers, repositoryType, beanManager, + return new CassandraRepositoryBean<>(cassandraOperationsBean, qualifiers, repositoryType, beanManager, Optional.of(getCustomImplementationDetector())); } diff --git a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/repository/config/CassandraRepositoryConfigurationExtension.java b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/repository/config/CassandraRepositoryConfigurationExtension.java index ee7f2391b..221c183b2 100644 --- a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/repository/config/CassandraRepositoryConfigurationExtension.java +++ b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/repository/config/CassandraRepositoryConfigurationExtension.java @@ -18,9 +18,9 @@ package org.springframework.data.cassandra.repository.config; import java.lang.annotation.Annotation; import java.util.Collection; import java.util.Collections; +import java.util.Optional; import org.springframework.beans.factory.support.BeanDefinitionBuilder; -import org.springframework.cassandra.config.xml.ParsingUtils; import org.springframework.data.cassandra.config.DefaultBeanNames; import org.springframework.data.cassandra.mapping.Table; import org.springframework.data.cassandra.repository.CassandraRepository; @@ -45,6 +45,14 @@ public class CassandraRepositoryConfigurationExtension extends RepositoryConfigu private static final String CASSANDRA_TEMPLATE_REF = "cassandra-template-ref"; + /* (non-Javadoc) + * @see org.springframework.data.repository.config.RepositoryConfigurationExtensionSupport#getModuleName() + */ + @Override + public String getModuleName() { + return "Cassandra"; + } + /* (non-Javadoc) * @see org.springframework.data.repository.config.RepositoryConfigurationExtensionSupport#getModulePrefix() */ @@ -53,14 +61,6 @@ public class CassandraRepositoryConfigurationExtension extends RepositoryConfigu return "cassandra"; } - /* (non-Javadoc) - * @see org.springframework.data.repository.config.RepositoryConfigurationExtension#getModuleName() - */ - @Override - public String getModuleName() { - return "Cassandra"; - } - /* (non-Javadoc) * @see org.springframework.data.repository.config.RepositoryConfigurationExtension#getRepositoryFactoryClassName() */ @@ -77,8 +77,11 @@ public class CassandraRepositoryConfigurationExtension extends RepositoryConfigu Element element = config.getElement(); - ParsingUtils.addOptionalPropertyReference(builder, "cassandraTemplate", element, CASSANDRA_TEMPLATE_REF, - DefaultBeanNames.DATA_TEMPLATE); + String cassandraTemplateRef = Optional.ofNullable(element.getAttribute(CASSANDRA_TEMPLATE_REF)) // + .filter(StringUtils::hasText) // + .orElse(DefaultBeanNames.DATA_TEMPLATE); + + builder.addPropertyReference("cassandraTemplate", cassandraTemplateRef); } /* (non-Javadoc) @@ -94,16 +97,16 @@ public class CassandraRepositoryConfigurationExtension extends RepositoryConfigu } } - /** - * @inheritDoc + /* (non-Javadoc) + * @see org.springframework.data.repository.config.RepositoryConfigurationExtensionSupport#getIdentifyingAnnotations() */ @Override protected Collection> getIdentifyingAnnotations() { return Collections.singleton(Table.class); } - /** - * @inheritDoc + /* (non-Javadoc) + * @see org.springframework.data.repository.config.RepositoryConfigurationExtensionSupport#getIdentifyingTypes() */ @Override protected Collection> getIdentifyingTypes() { diff --git a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/repository/config/ReactiveCassandraRepositoryConfigurationExtension.java b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/repository/config/ReactiveCassandraRepositoryConfigurationExtension.java index 6b332b697..cc3fbcee7 100644 --- a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/repository/config/ReactiveCassandraRepositoryConfigurationExtension.java +++ b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/repository/config/ReactiveCassandraRepositoryConfigurationExtension.java @@ -34,24 +34,24 @@ import org.springframework.util.StringUtils; */ public class ReactiveCassandraRepositoryConfigurationExtension extends CassandraRepositoryConfigurationExtension { - /** - * @inheritDoc + /* (non-Javadoc) + * @see org.springframework.data.cassandra.repository.config.CassandraRepositoryConfigurationExtension#getModuleName() */ @Override public String getModuleName() { return "Reactive Cassandra"; } - /** - * @inheritDoc + /* (non-Javadoc) + * @see org.springframework.data.cassandra.repository.config.CassandraRepositoryConfigurationExtension#getRepositoryFactoryClassName() */ @Override public String getRepositoryFactoryClassName() { return ReactiveCassandraRepositoryFactoryBean.class.getName(); } - /** - * @inheritDoc + /* (non-Javadoc) + * @see org.springframework.data.cassandra.repository.config.CassandraRepositoryConfigurationExtension#postProcess(org.springframework.beans.factory.support.BeanDefinitionBuilder, org.springframework.data.repository.config.AnnotationRepositoryConfigurationSource) */ @Override public void postProcess(BeanDefinitionBuilder builder, AnnotationRepositoryConfigurationSource config) { @@ -63,8 +63,8 @@ public class ReactiveCassandraRepositoryConfigurationExtension extends Cassandra } } - /** - * @inheritDoc + /* (non-Javadoc) + * @see org.springframework.data.cassandra.repository.config.CassandraRepositoryConfigurationExtension#getIdentifyingTypes() */ @Override protected Collection> getIdentifyingTypes() { diff --git a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/repository/query/AbstractCassandraQuery.java b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/repository/query/AbstractCassandraQuery.java index 5f208fb1d..fc38e2903 100644 --- a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/repository/query/AbstractCassandraQuery.java +++ b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/repository/query/AbstractCassandraQuery.java @@ -158,11 +158,11 @@ public abstract class AbstractCassandraQuery implements RepositoryQuery { Collection results; if (ClassUtils.isAssignable(SortedSet.class, declaredReturnType)) { - results = new TreeSet(); + results = new TreeSet<>(); } else if (ClassUtils.isAssignable(Set.class, declaredReturnType)) { - results = new HashSet(); + results = new HashSet<>(); } else { // List.class, Collection.class, or array - results = new ArrayList(); + results = new ArrayList<>(); } CassandraConverter converter = template.getConverter(); diff --git a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/repository/query/CassandraQueryCreator.java b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/repository/query/CassandraQueryCreator.java index 892702f80..4b8c3a99f 100644 --- a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/repository/query/CassandraQueryCreator.java +++ b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/repository/query/CassandraQueryCreator.java @@ -1,5 +1,5 @@ /* - * Copyright 2010-2016 the original author or authors. + * Copyright 2010-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. @@ -234,7 +234,7 @@ class CassandraQueryCreator extends AbstractQueryCreator { */ static class WhereBuilder { - private List clauses = new ArrayList(); + private List clauses = new ArrayList<>(); Clause and(Clause clause) { clauses.add(clause); diff --git a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/repository/query/CassandraQueryMethod.java b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/repository/query/CassandraQueryMethod.java index 0175ef3a7..574ec08b3 100644 --- a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/repository/query/CassandraQueryMethod.java +++ b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/repository/query/CassandraQueryMethod.java @@ -97,7 +97,7 @@ public class CassandraQueryMethod extends QueryMethod { Class domainClass = getDomainClass(); if (ClassUtils.isPrimitiveOrWrapper(returnedObjectType)) { - this.entityMetadata = new SimpleCassandraEntityMetadata((Class) domainClass, + this.entityMetadata = new SimpleCassandraEntityMetadata<>((Class) domainClass, mappingContext.getRequiredPersistentEntity(domainClass)); } else { @@ -113,7 +113,7 @@ public class CassandraQueryMethod extends QueryMethod { CassandraPersistentEntity collectionEntity = domainClass.isAssignableFrom(returnedObjectType) ? returnedEntity : managedEntity; - this.entityMetadata = new SimpleCassandraEntityMetadata((Class) returnedEntity.getType(), + this.entityMetadata = new SimpleCassandraEntityMetadata<>((Class) returnedEntity.getType(), collectionEntity); } diff --git a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/repository/query/ExpressionEvaluatingParameterBinder.java b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/repository/query/ExpressionEvaluatingParameterBinder.java index fe571de69..92b1b650c 100644 --- a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/repository/query/ExpressionEvaluatingParameterBinder.java +++ b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/repository/query/ExpressionEvaluatingParameterBinder.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2016-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -69,11 +69,12 @@ class ExpressionEvaluatingParameterBinder { return Collections.emptyList(); } - List parameters = new ArrayList(bindingContext.getBindings().size()); + List parameters = new ArrayList<>(bindingContext.getBindings().size()); - for (ParameterBinding binding : bindingContext.getBindings()) { - parameters.add(getParameterValueForBinding(parameterAccessor, bindingContext.getParameters(), binding)); - } + bindingContext.getBindings() // + .stream() // + .map(binding -> getParameterValueForBinding(parameterAccessor, bindingContext.getParameters(), binding)) // + .forEach(parameters::add); return parameters; } diff --git a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/repository/query/StringBasedQuery.java b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/repository/query/StringBasedQuery.java index c455bb6f9..8ffcab9d9 100644 --- a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/repository/query/StringBasedQuery.java +++ b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/repository/query/StringBasedQuery.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2016-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -361,14 +361,14 @@ class StringBasedQuery { private static Matcher findNextBindingOrExpression(String input, int position) { - List matchers = new ArrayList(); + List matchers = new ArrayList<>(); matchers.add(INDEX_PARAMETER_BINDING_PATTERN.matcher(input)); matchers.add(NAMED_PARAMETER_BINDING_PATTERN.matcher(input)); matchers.add(INDEX_BASED_EXPRESSION_PATTERN.matcher(input)); matchers.add(NAME_BASED_EXPRESSION_PATTERN.matcher(input)); - TreeMap matcherMap = new TreeMap(); + TreeMap matcherMap = new TreeMap<>(); for (Matcher matcher : matchers) { if (matcher.find(position)) { diff --git a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/repository/support/CassandraRepositoryFactory.java b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/repository/support/CassandraRepositoryFactory.java index d997d5e8b..3d73fa022 100644 --- a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/repository/support/CassandraRepositoryFactory.java +++ b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/repository/support/CassandraRepositoryFactory.java @@ -99,7 +99,7 @@ public class CassandraRepositoryFactory extends RepositoryFactorySupport { - return new MappingCassandraEntityInformation((CassandraPersistentEntity) entity, + return new MappingCassandraEntityInformation<>((CassandraPersistentEntity) entity, operations.getConverter()); } diff --git a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/repository/support/IdInterfaceExceptions.java b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/repository/support/IdInterfaceExceptions.java index 6d93d62b1..13b32a40e 100644 --- a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/repository/support/IdInterfaceExceptions.java +++ b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/repository/support/IdInterfaceExceptions.java @@ -1,12 +1,12 @@ /* - * Copyright 2013-2014 the original author or authors - * + * Copyright 2013-2017 the original author or authors + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. @@ -17,17 +17,18 @@ package org.springframework.data.cassandra.repository.support; import java.util.Collection; import java.util.LinkedList; +import java.util.stream.Collectors; /** * Aggregator of multiple violations for convenience when verifying id interfaces. This allows the framework to * communicate all errors at once, rather than one at a time. - * + * * @author Matthew T. Adams */ @SuppressWarnings("serial") public class IdInterfaceExceptions extends RuntimeException { - Collection exceptions = new LinkedList(); + Collection exceptions = new LinkedList<>(); String idInterfaceName; public IdInterfaceExceptions(Class idInterface) { @@ -49,11 +50,7 @@ public class IdInterfaceExceptions extends RuntimeException { * Returns a list of the {@link IdInterfaceException} messages aggregated within. */ public Collection getMessages() { - Collection messages = new LinkedList(); - for (IdInterfaceException e : exceptions) { - messages.add(e.getMessage()); - } - return messages; + return exceptions.stream().map(Throwable::getMessage).collect(Collectors.toList()); } /** diff --git a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/repository/support/IdInterfaceValidator.java b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/repository/support/IdInterfaceValidator.java index 0439098c0..a256e321e 100644 --- a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/repository/support/IdInterfaceValidator.java +++ b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/repository/support/IdInterfaceValidator.java @@ -1,3 +1,18 @@ +/* + * 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.cassandra.repository.support; import java.io.Serializable; @@ -15,29 +30,29 @@ public class IdInterfaceValidator { *

* Id interfaces are intended to have methods representing setters and getters. Getter methods take the form *

    - *
  • PropertyType getPropertyName() or
  • - *
  • PropertyType propertyName().
  • + *
  • {@code PropertyType getPropertyName()} or
  • + *
  • {@code PropertyType propertyName()}.
  • *
* Setter methods take the form *
    - *
  • void|IdType setPropertyName(PropertyType),
  • - *
  • void|IdType withPropertyName(PropertyType), or
  • - *
  • void|IdType propertyName(PropertyType);
  • + *
  • {@code void|IdType setPropertyName(PropertyType)},
  • + *
  • {@code void|IdType withPropertyName(PropertyType)}, or
  • + *
  • {@code void|IdType propertyName(PropertyType)};
  • *
* setter methods may also declare that they return their id interface type to support method chaining. *

* Id interfaces *

    - *
  • must be an interface, not a class,
  • + *
  • must be an {@code interface}, not a class,
  • *
  • may extend {@link Serializable},
  • *
  • may extend {@link MapId},
  • *
  • must have getter methods that only return a {@link Serializable} type,
  • *
  • must have setter methods that only take a single {@link Serializable} type,
  • - *
  • must have setter methods that only return void or the id interface's type,
  • + *
  • must have setter methods that only return {@code void} or the id interface's type,
  • *
  • must not define any getter methods with the literal name "get", and
  • *
  • must not define any setter methods with the literal names "set" or "with".
  • *
- * + * * @param id The candidate interface type * @throws IdInterfaceExceptions * @see IdInterfaceExceptions#getExceptions() diff --git a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/repository/support/MapIdProxyDelegate.java b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/repository/support/MapIdProxyDelegate.java index 3a77367c1..e4d5b73ec 100644 --- a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/repository/support/MapIdProxyDelegate.java +++ b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/repository/support/MapIdProxyDelegate.java @@ -1,18 +1,33 @@ +/* + * 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.cassandra.repository.support; import java.io.Serializable; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.util.Arrays; -import java.util.HashMap; import java.util.Map; +import java.util.stream.Collectors; import org.springframework.data.cassandra.repository.MapId; import org.springframework.util.StringUtils; /** * Delegate class for dynamic proxies of id interfaces; delegates to {@link BasicMapId}. - * + * * @see MapIdFactory#id(Class) * @see MapIdFactory#id(Class, ClassLoader) * @author Matthew T. Adams @@ -23,11 +38,9 @@ class MapIdProxyDelegate implements InvocationHandler { static { Method[] mapIdMethods = MapId.class.getMethods(); - MAP_ID_SIGNATURES = new HashMap(mapIdMethods.length); - for (Method m : mapIdMethods) { - Signature s = new Signature(m, true); - MAP_ID_SIGNATURES.put(s, s); - } + MAP_ID_SIGNATURES = Arrays.stream(mapIdMethods).map(m -> new Signature(m, true)) + .collect(Collectors.toMap(o -> o, o -> o)); + } private MapId delegate = new BasicMapId(); @@ -44,8 +57,8 @@ class MapIdProxyDelegate implements InvocationHandler { } if (args != null && args.length > 1) { - throw new IllegalArgumentException(String.format("Method [%s] on interface [%s] must take zero or one argument", - method, idInterface)); + throw new IllegalArgumentException( + String.format("Method [%s] on interface [%s] must take zero or one argument", method, idInterface)); } boolean isSetter = args != null && args.length == 1; @@ -83,10 +96,11 @@ class MapIdProxyDelegate implements InvocationHandler { int length = name.length(); if (isSet || isWith) { if (length < minLength) { - throw new IllegalArgumentException(String.format("Method [%s] on interface [%s] must be of form " - + "' set()', " - + "' with()' or " - + "' ()'", name, idInterface)); + throw new IllegalArgumentException(String.format( + "Method [%s] on interface [%s] must be of form " + "' set()', " + + "' with()' or " + + "' ()'", + name, idInterface)); } name = StringUtils.uncapitalize(name.substring(minLength - 1)); } @@ -96,8 +110,8 @@ class MapIdProxyDelegate implements InvocationHandler { return; } if (!(value instanceof Serializable)) { - throw new IllegalArgumentException(String.format("Given object [%s] must implement %s", value, - Serializable.class.getName())); + throw new IllegalArgumentException( + String.format("Given object [%s] must implement %s", value, Serializable.class.getName())); } delegate.put(name, (Serializable) value); } diff --git a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/repository/support/SimpleCassandraRepository.java b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/repository/support/SimpleCassandraRepository.java index c87c52a44..484393757 100644 --- a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/repository/support/SimpleCassandraRepository.java +++ b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/repository/support/SimpleCassandraRepository.java @@ -75,10 +75,7 @@ public class SimpleCassandraRepository implements Ty @Override public List save(Iterable entities) { - Assert.notNull(entities, "The given Iterable of entities must not be null"); - - List result = new ArrayList<>(); - + Assert.notNull(entities, "The given Iterable of entities must not be null");List result = new ArrayList<>(); for (S entity : entities) { S saved; @@ -213,9 +210,7 @@ public class SimpleCassandraRepository implements Ty Assert.notNull(entities, "The given Iterable of entities must not be null"); - for (T entity : entities) { - operations.delete(entity); - } + entities.forEach(operations::delete); } /* (non-Javadoc) diff --git a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/util/CqlUtils.java b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/util/CqlUtils.java index ec14d357c..f44f4dda2 100644 --- a/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/util/CqlUtils.java +++ b/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/util/CqlUtils.java @@ -1,12 +1,12 @@ /* - * Copyright 2013-2014 the original author or authors - * + * Copyright 2013-2017 the original author or authors + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. @@ -29,7 +29,7 @@ import com.datastax.driver.core.TableMetadata; /** * Utilities to convert Cassandra Annotated objects to Queries and CQL. - * + * * @author Alex Shvid * @author David Webb * @author Matthew T. Adams @@ -40,7 +40,7 @@ public abstract class CqlUtils { /** * Alter the table to reflect the entity annotations - * + * * @param tableName * @param entity * @param table @@ -48,42 +48,39 @@ public abstract class CqlUtils { */ public static List alterTable(final String tableName, final CassandraPersistentEntity entity, final TableMetadata table) { - final List result = new ArrayList(); + final List result = new ArrayList<>(); - entity.doWithProperties(new PropertyHandler() { - @Override - public void doWithPersistentProperty(CassandraPersistentProperty prop) { + entity.doWithProperties((PropertyHandler) prop -> { - String columnName = prop.getColumnName().toCql(); - DataType columnDataType = prop.getDataType(); - ColumnMetadata columnMetadata = table.getColumn(columnName.toLowerCase()); - - if (columnMetadata != null && columnDataType.equals(columnMetadata.getType())) { - return; - } - - final StringBuilder str = new StringBuilder(); - str.append("ALTER TABLE "); - str.append(tableName); - if (columnMetadata == null) { - str.append(" ADD "); - } else { - str.append(" ALTER "); - } - - str.append(columnName); - str.append(' '); - - if (columnMetadata != null) { - str.append("TYPE "); - } - - str.append(CqlStringUtils.toCql(columnDataType)); - - str.append(';'); - result.add(str.toString()); + String columnName = prop.getColumnName().toCql(); + DataType columnDataType = prop.getDataType(); + ColumnMetadata columnMetadata = table.getColumn(columnName.toLowerCase()); + if (columnMetadata != null && columnDataType.equals(columnMetadata.getType())) { + return; } + + final StringBuilder str = new StringBuilder(); + str.append("ALTER TABLE "); + str.append(tableName); + if (columnMetadata == null) { + str.append(" ADD "); + } else { + str.append(" ALTER "); + } + + str.append(columnName); + str.append(' '); + + if (columnMetadata != null) { + str.append("TYPE "); + } + + str.append(CqlStringUtils.toCql(columnDataType)); + + str.append(';'); + result.add(str.toString()); + }); return result; diff --git a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/RowMockUtil.java b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/RowMockUtil.java index 3c3b48986..87bf449c0 100644 --- a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/RowMockUtil.java +++ b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/RowMockUtil.java @@ -19,8 +19,8 @@ import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.*; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; +import java.util.Arrays; + import org.springframework.util.Assert; import com.datastax.driver.core.ColumnDefinitions; @@ -50,75 +50,43 @@ public class RowMockUtil { when(rowMock.getColumnDefinitions()).thenReturn(columnDefinitionsMock); - when(columnDefinitionsMock.contains(anyString())).thenAnswer(new Answer() { - @Override - public Boolean answer(InvocationOnMock invocation) throws Throwable { + when(columnDefinitionsMock.contains(anyString())).thenAnswer(invocation -> Arrays.stream(columns) + .anyMatch(column -> column.name.equalsIgnoreCase((String) invocation.getArguments()[0]))); - for (Column column : columns) { - if (column.name.equalsIgnoreCase((String) invocation.getArguments()[0])) { - return true; - } + when(columnDefinitionsMock.getIndexOf(anyString())).thenAnswer(invocation -> { + + int counter = 0; + for (Column column : columns) { + if (column.name.equalsIgnoreCase((String) invocation.getArguments()[0])) { + return counter; } - - return false; + counter++; } - }); - when(columnDefinitionsMock.getIndexOf(anyString())).thenAnswer(new Answer() { - @Override - public Integer answer(InvocationOnMock invocation) throws Throwable { - - int counter = 0; - for (Column column : columns) { - if (column.name.equalsIgnoreCase((String) invocation.getArguments()[0])) { - return counter; - } - counter++; - } - - return -1; - } + return -1; }); when(columnDefinitionsMock.getType(anyString())).thenAnswer(new Answer() { @Override public DataType answer(InvocationOnMock invocation) throws Throwable { - for (Column column : columns) { - if (column.name.equalsIgnoreCase((String) invocation.getArguments()[0])) { - return column.type; - } - } - - return null; + return Arrays.stream(columns) + .filter(column -> column.name.equalsIgnoreCase((String) invocation.getArguments()[0])).findFirst() + .map(column -> column.type).orElse(null); } }); - when(columnDefinitionsMock.getType(anyInt())).thenAnswer(new Answer() { - @Override - public DataType answer(InvocationOnMock invocation) throws Throwable { - return columns[(Integer) invocation.getArguments()[0]].type; - } - }); + when(columnDefinitionsMock.getType(anyInt())) + .thenAnswer(invocation -> columns[(Integer) invocation.getArguments()[0]].type); - when(rowMock.getObject(anyInt())).thenAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - return columns[(Integer) invocation.getArguments()[0]].value; - } - }); + when(rowMock.getObject(anyInt())).thenAnswer(invocation -> columns[(Integer) invocation.getArguments()[0]].value); when(rowMock.getObject(anyString())).thenAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { - - for (Column column : columns) { - if (column.name.equalsIgnoreCase((String) invocation.getArguments()[0])) { - return column.value; - } - } - - return null; + return Arrays.stream(columns) + .filter(column -> column.name.equalsIgnoreCase((String) invocation.getArguments()[0])).findFirst() + .map(column -> column.value).orElse(null); } }); diff --git a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/config/CassandraSessionFactoryBeanUnitTests.java b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/config/CassandraSessionFactoryBeanUnitTests.java index 38ef08b88..dd52e0361 100755 --- a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/config/CassandraSessionFactoryBeanUnitTests.java +++ b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/config/CassandraSessionFactoryBeanUnitTests.java @@ -28,9 +28,7 @@ import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.Mock; -import org.mockito.invocation.InvocationOnMock; import org.mockito.runners.MockitoJUnitRunner; -import org.mockito.stubbing.Answer; import org.springframework.cassandra.core.cql.CqlIdentifier; import org.springframework.data.cassandra.convert.CassandraConverter; @@ -72,12 +70,9 @@ public class CassandraSessionFactoryBeanUnitTests { @Test // DATACASS-219 public void afterPropertiesSetPerformsSchemaAction() throws Exception { - doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock invocationOnMock) throws Throwable { - assertThat(factoryBean.getSchemaAction()).isEqualTo(SchemaAction.RECREATE); - return null; - } + doAnswer(invocationOnMock -> { + assertThat(factoryBean.getSchemaAction()).isEqualTo(SchemaAction.RECREATE); + return null; }).when(factoryBean).performSchemaAction(); factoryBean.setConverter(mockConverter); @@ -107,14 +102,11 @@ public class CassandraSessionFactoryBeanUnitTests { private void performSchemaActionCallsCreateTableWithArgumentsMatchingTheSchemaAction(SchemaAction schemaAction, final boolean dropTables, final boolean dropUnused, final boolean ifNotExists) { - doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock invocationOnMock) throws Throwable { - assertThat(invocationOnMock.getArgumentAt(0, Boolean.class)).isEqualTo(dropTables); - assertThat(invocationOnMock.getArgumentAt(1, Boolean.class)).isEqualTo(dropUnused); - assertThat(invocationOnMock.getArgumentAt(2, Boolean.class)).isEqualTo(ifNotExists); - return null; - } + doAnswer(invocationOnMock -> { + assertThat(invocationOnMock.getArgumentAt(0, Boolean.class)).isEqualTo(dropTables); + assertThat(invocationOnMock.getArgumentAt(1, Boolean.class)).isEqualTo(dropUnused); + assertThat(invocationOnMock.getArgumentAt(2, Boolean.class)).isEqualTo(ifNotExists); + return null; }).when(factoryBean).createTables(anyBoolean(), anyBoolean(), anyBoolean()); factoryBean.setSchemaAction(schemaAction); diff --git a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/config/SchemaActionIntegrationTests.java b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/config/SchemaActionIntegrationTests.java index 39b790fbe..90aca39cb 100755 --- a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/config/SchemaActionIntegrationTests.java +++ b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/config/SchemaActionIntegrationTests.java @@ -33,7 +33,6 @@ import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.dao.DataAccessException; import org.springframework.data.cassandra.config.java.AbstractCassandraConfiguration; import org.springframework.data.cassandra.test.integration.repository.querymethods.declared.Person; @@ -103,13 +102,10 @@ public class SchemaActionIntegrationTests extends AbstractEmbeddedCassandraInteg @Test public void createWithNoExistingTableCreatesTableFromEntity() { - doInSessionWithConfiguration(CreateWithNoExistingTableConfiguration.class, new SessionCallback() { - @Override - public Void doInSession(Session session) throws DataAccessException { - assertHasTableWithColumns(session, "person", "firstName", "lastName", "nickname", "birthDate", - "numberOfChildren", "cool", "createdDate", "zoneId", "mainAddress", "alternativeAddresses"); - return null; - } + doInSessionWithConfiguration(CreateWithNoExistingTableConfiguration.class, (SessionCallback) session -> { + assertHasTableWithColumns(session, "person", "firstName", "lastName", "nickname", "birthDate", "numberOfChildren", + "cool", "createdDate", "zoneId", "mainAddress", "alternativeAddresses"); + return null; }); } @@ -117,12 +113,9 @@ public class SchemaActionIntegrationTests extends AbstractEmbeddedCassandraInteg public void createWithExistingTableThrowsErrorWhenCreatingTableFromEntity() { try { - doInSessionWithConfiguration(CreateWithExistingTableConfiguration.class, new SessionCallback() { - @Override - public Object doInSession(Session s) throws DataAccessException { - fail(String.format("%s should have failed!", CreateWithExistingTableConfiguration.class.getSimpleName())); - return null; - } + doInSessionWithConfiguration(CreateWithExistingTableConfiguration.class, s -> { + fail(String.format("%s should have failed!", CreateWithExistingTableConfiguration.class.getSimpleName())); + return null; }); fail("Missing BeanCreationException"); } catch (BeanCreationException e) { @@ -132,36 +125,30 @@ public class SchemaActionIntegrationTests extends AbstractEmbeddedCassandraInteg @Test public void createIfNotExistsWithNoExistingTableCreatesTableFromEntity() { - doInSessionWithConfiguration(CreateIfNotExistsWithNoExistingTableConfiguration.class, new SessionCallback() { - @Override - public Void doInSession(Session session) throws DataAccessException { - assertHasTableWithColumns(session, "person", "firstName", "lastName", "nickname", "birthDate", - "numberOfChildren", "cool", "createdDate", "zoneId", "mainAddress", "alternativeAddresses"); - return null; - } + doInSessionWithConfiguration(CreateIfNotExistsWithNoExistingTableConfiguration.class, + (SessionCallback) session -> { + assertHasTableWithColumns(session, "person", "firstName", "lastName", "nickname", "birthDate", + "numberOfChildren", "cool", "createdDate", "zoneId", "mainAddress", "alternativeAddresses"); + return null; }); } @Test public void createIfNotExistsWithExistingTableUsesExistingTable() { - doInSessionWithConfiguration(CreateIfNotExistsWithExistingTableConfiguration.class, new SessionCallback() { - @Override - public Void doInSession(Session session) throws DataAccessException { - assertHasTableWithColumns(session, "person", "id", "firstName", "lastName"); - return null; - } + doInSessionWithConfiguration(CreateIfNotExistsWithExistingTableConfiguration.class, + (SessionCallback) session -> { + assertHasTableWithColumns(session, "person", "id", "firstName", "lastName"); + return null; }); } @Test public void recreateTableFromEntityDropsExistingTable() { - doInSessionWithConfiguration(RecreateSchemaActionWithExistingTableConfiguration.class, new SessionCallback() { - @Override - public Void doInSession(Session session) throws DataAccessException { - assertHasTableWithColumns(session, "person", "firstName", "lastName", "nickname", "birthDate", - "numberOfChildren", "cool", "createdDate", "zoneId", "mainAddress", "alternativeAddresses"); - return null; - } + doInSessionWithConfiguration(RecreateSchemaActionWithExistingTableConfiguration.class, + (SessionCallback) session -> { + assertHasTableWithColumns(session, "person", "firstName", "lastName", "nickname", "birthDate", + "numberOfChildren", "cool", "createdDate", "zoneId", "mainAddress", "alternativeAddresses"); + return null; }); } diff --git a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/convert/CassandraTypeMappingIntegrationTest.java b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/convert/CassandraTypeMappingIntegrationTest.java index f854e7bbb..173470cd1 100755 --- a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/convert/CassandraTypeMappingIntegrationTest.java +++ b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/convert/CassandraTypeMappingIntegrationTest.java @@ -335,7 +335,7 @@ public class CassandraTypeMappingIntegrationTest extends AbstractKeyspaceCreatin public void shouldReadAndWriteEmptySetOfString() { AllPossibleTypes entity = new AllPossibleTypes("1"); - entity.setSetOfString(new HashSet()); + entity.setSetOfString(new HashSet<>()); operations.insert(entity); AllPossibleTypes loaded = load(entity); @@ -359,7 +359,7 @@ public class CassandraTypeMappingIntegrationTest extends AbstractKeyspaceCreatin public void shouldReadAndWriteEmptyListOfString() { AllPossibleTypes entity = new AllPossibleTypes("1"); - entity.setListOfString(new ArrayList()); + entity.setListOfString(new ArrayList<>()); operations.insert(entity); AllPossibleTypes loaded = load(entity); @@ -383,7 +383,7 @@ public class CassandraTypeMappingIntegrationTest extends AbstractKeyspaceCreatin public void shouldReadAndWriteEmptyMapOfString() { AllPossibleTypes entity = new AllPossibleTypes("1"); - entity.setMapOfString(new HashMap()); + entity.setMapOfString(new HashMap<>()); operations.insert(entity); AllPossibleTypes loaded = load(entity); @@ -617,6 +617,6 @@ public class CassandraTypeMappingIntegrationTest extends AbstractKeyspaceCreatin } public enum Condition { - MINT; + MINT } } diff --git a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/convert/CustomConversionIntegrationTests.java b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/convert/CustomConversionIntegrationTests.java index 9a65cb911..0e6c8eddd 100755 --- a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/convert/CustomConversionIntegrationTests.java +++ b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/convert/CustomConversionIntegrationTests.java @@ -56,7 +56,7 @@ public class CustomConversionIntegrationTests extends AbstractKeyspaceCreatingIn @Before public void setUp() { - List> converters = new ArrayList>(); + List> converters = new ArrayList<>(); converters.add(new PersonReadConverter()); converters.add(new PersonWriteConverter()); CustomConversions customConversions = new CustomConversions(converters); diff --git a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/convert/CustomConversionsUnitTests.java b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/convert/CustomConversionsUnitTests.java index 4da0e4be7..e66ccdfe1 100755 --- a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/convert/CustomConversionsUnitTests.java +++ b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/convert/CustomConversionsUnitTests.java @@ -73,7 +73,7 @@ public class CustomConversionsUnitTests { @Test // DATACASS-280 public void considersTypesWeRegisteredConvertersForAsSimple() { - CustomConversions conversions = new CustomConversions(Arrays.asList(FormatToStringConverter.INSTANCE)); + CustomConversions conversions = new CustomConversions(Collections.singletonList(FormatToStringConverter.INSTANCE)); assertThat(conversions.isSimpleType(UUID.class)).isTrue(); } @@ -82,7 +82,7 @@ public class CustomConversionsUnitTests { GenericConversionService conversionService = new DefaultConversionService(); - CustomConversions conversions = new CustomConversions(Arrays.asList(StringToFormatConverter.INSTANCE)); + CustomConversions conversions = new CustomConversions(Collections.singletonList(StringToFormatConverter.INSTANCE)); conversions.registerConvertersIn(conversionService); assertThat(conversionService.canConvert(String.class, Format.class)).isTrue(); @@ -91,14 +91,14 @@ public class CustomConversionsUnitTests { @Test // DATACASS-280 public void doesNotConsiderTypeSimpleIfOnlyReadConverterIsRegistered() { - CustomConversions conversions = new CustomConversions(Arrays.asList(StringToFormatConverter.INSTANCE)); + CustomConversions conversions = new CustomConversions(Collections.singletonList(StringToFormatConverter.INSTANCE)); assertThat(conversions.isSimpleType(Format.class)).isFalse(); } @Test // DATACASS-280 public void discoversConvertersForSubtypesOfCassandraTypes() { - CustomConversions conversions = new CustomConversions(Arrays.asList(StringToIntegerConverter.INSTANCE)); + CustomConversions conversions = new CustomConversions(Collections.singletonList(StringToIntegerConverter.INSTANCE)); assertThat(conversions.hasCustomReadTarget(String.class, Integer.class)).isTrue(); assertThat(conversions.hasCustomWriteTarget(String.class, Integer.class)).isTrue(); } @@ -128,14 +128,15 @@ public class CustomConversionsUnitTests { @SuppressWarnings("rawtypes") public void favorsCustomConverterForIndeterminedTargetType() { - CustomConversions conversions = new CustomConversions(Arrays.asList(DateTimeToStringConverter.INSTANCE)); + CustomConversions conversions = new CustomConversions( + Collections.singletonList(DateTimeToStringConverter.INSTANCE)); assertThat(conversions.getCustomWriteTarget(DateTime.class, null)).isEqualTo((Class) String.class); } @Test // DATACASS-280 public void customConverterOverridesDefault() { - CustomConversions conversions = new CustomConversions(Arrays.asList(CustomDateTimeConverter.INSTANCE)); + CustomConversions conversions = new CustomConversions(Collections.singletonList(CustomDateTimeConverter.INSTANCE)); GenericConversionService conversionService = new DefaultConversionService(); conversions.registerConvertersIn(conversionService); @@ -145,14 +146,15 @@ public class CustomConversionsUnitTests { @Test // DATACASS-280 public void shouldSelectPropertCustomWriteTargetForCglibProxiedType() { - CustomConversions conversions = new CustomConversions(Arrays.asList(FormatToStringConverter.INSTANCE)); + CustomConversions conversions = new CustomConversions(Collections.singletonList(FormatToStringConverter.INSTANCE)); assertThat(conversions.getCustomWriteTarget(createProxyTypeFor(Format.class))).isAssignableFrom(String.class); } @Test // DATACASS-280 public void shouldSelectPropertyCustomReadTargetForCglibProxiedType() { - CustomConversions conversions = new CustomConversions(Arrays.asList(CustomObjectToStringConverter.INSTANCE)); + CustomConversions conversions = new CustomConversions( + Collections.singletonList(CustomObjectToStringConverter.INSTANCE)); assertThat(conversions.hasCustomReadTarget(createProxyTypeFor(Object.class), String.class)).isTrue(); } @@ -269,7 +271,7 @@ public class CustomConversionsUnitTests { @Override public Converter getConverter(Class targetType) { - return new StringToFormat(targetType); + return new StringToFormat<>(targetType); } private static final class StringToFormat implements Converter { diff --git a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/convert/MappingCassandraConverterUnitTests.java b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/convert/MappingCassandraConverterUnitTests.java index e73eeaad5..ecfbb25d9 100755 --- a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/convert/MappingCassandraConverterUnitTests.java +++ b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/convert/MappingCassandraConverterUnitTests.java @@ -457,7 +457,7 @@ public class MappingCassandraConverterUnitTests { java.time.LocalDate localDate = java.time.LocalDate.of(2010, 7, 4); TypeWithLocalDate typeWithLocalDate = new TypeWithLocalDate(); - typeWithLocalDate.set = new HashSet(Arrays.asList(now, localDate)); + typeWithLocalDate.set = new HashSet<>(Arrays.asList(now, localDate)); Insert insert = QueryBuilder.insertInto("table"); @@ -846,28 +846,16 @@ public class MappingCassandraConverterUnitTests { @SuppressWarnings("unchecked") private List getListValue(Insert statement) { + List values = getValues(statement); - - for (Object value : values) { - if (value instanceof List) { - return (List) value; - } - } - - return null; + return (List) values.stream().filter(value -> value instanceof List).findFirst().orElse(null); } @SuppressWarnings("unchecked") private Set getSetValue(Insert statement) { + List values = getValues(statement); - - for (Object value : values) { - if (value instanceof Set) { - return (Set) value; - } - } - - return null; + return (Set) values.stream().filter(value -> value instanceof Set).findFirst().orElse(null); } @SuppressWarnings("unchecked") @@ -883,7 +871,7 @@ public class MappingCassandraConverterUnitTests { @SuppressWarnings("unchecked") private Map getAssignments(Update statement) { - Map result = new LinkedHashMap(); + Map result = new LinkedHashMap<>(); Assignments assignments = (Assignments) ReflectionTestUtils.getField(statement, "assignments"); @@ -915,12 +903,12 @@ public class MappingCassandraConverterUnitTests { @SuppressWarnings("unchecked") private Map getWherePredicates(BuiltStatement where) { - Map result = new LinkedHashMap(); + Map result = new LinkedHashMap<>(); List clauses = (List) ReflectionTestUtils.getField(where, "clauses"); for (Clause clause : clauses) { - result.put((String) ReflectionTestUtils.invokeMethod(clause, "name"), + result.put(ReflectionTestUtils.invokeMethod(clause, "name"), ReflectionTestUtils.getField(clause, "value")); } @@ -1030,7 +1018,7 @@ public class MappingCassandraConverterUnitTests { } public enum Condition { - MINT, USED; + MINT, USED } @Table diff --git a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/core/AsyncCassandraTemplateUnitTests.java b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/core/AsyncCassandraTemplateUnitTests.java index a9b8b2c6c..56c6b08e2 100644 --- a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/core/AsyncCassandraTemplateUnitTests.java +++ b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/core/AsyncCassandraTemplateUnitTests.java @@ -53,7 +53,7 @@ import com.google.common.util.concurrent.AbstractFuture; /** * Unit tests for {@link AsyncCassandraTemplate}. - * + * * @author Mark Paluch */ @RunWith(MockitoJUnitRunner.class) @@ -426,7 +426,7 @@ public class AsyncCassandraTemplateUnitTests { /** * Create a completed future that reports a failure given {@link Throwable}. - * + * * @param throwable must not be {@literal null}. * @return the completed/failed {@link TestResultSetFuture}. */ diff --git a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/core/CassandraPersistentEntitySchemaCreatorUnitTests.java b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/core/CassandraPersistentEntitySchemaCreatorUnitTests.java index 1a7d4a8da..1a4d12314 100644 --- a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/core/CassandraPersistentEntitySchemaCreatorUnitTests.java +++ b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/core/CassandraPersistentEntitySchemaCreatorUnitTests.java @@ -15,6 +15,7 @@ */ package org.springframework.data.cassandra.core; +import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import java.util.List; @@ -28,12 +29,8 @@ import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.cassandra.core.CqlOperations; -import org.springframework.cassandra.core.cql.CqlIdentifier; import org.springframework.data.cassandra.mapping.BasicCassandraMappingContext; import org.springframework.data.cassandra.mapping.UserDefinedType; -import org.springframework.data.cassandra.mapping.UserTypeResolver; - -import com.datastax.driver.core.UserType; /** * Unit tests for {@link CassandraPersistentEntitySchemaCreator}. @@ -52,13 +49,10 @@ public class CassandraPersistentEntitySchemaCreatorUnitTests { @Before public void setUp() throws Exception { - context.setUserTypeResolver(new UserTypeResolver() { - @Override - public UserType resolveType(CqlIdentifier typeName) { - // make sure that calls to this method pop up. Calling UserTypeResolver while resolving - // to be created user types isn't a good idea because they do not exist at resolution time. - throw new IllegalArgumentException(String.format("Type %s not found", typeName)); - } + context.setUserTypeResolver(typeName -> { + // make sure that calls to this method pop up. Calling UserTypeResolver while resolving + // to be created user types isn't a good idea because they do not exist at resolution time. + throw new IllegalArgumentException(String.format("Type %s not found", typeName)); }); when(adminOperations.getCqlOperations()).thenReturn(operations); diff --git a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/core/CassandraPersistentEntitySchemaDropperUnitTests.java b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/core/CassandraPersistentEntitySchemaDropperUnitTests.java index ed050b52f..728d47f1f 100644 --- a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/core/CassandraPersistentEntitySchemaDropperUnitTests.java +++ b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/core/CassandraPersistentEntitySchemaDropperUnitTests.java @@ -33,7 +33,6 @@ import org.springframework.data.annotation.Id; import org.springframework.data.cassandra.mapping.BasicCassandraMappingContext; import org.springframework.data.cassandra.mapping.Table; import org.springframework.data.cassandra.mapping.UserDefinedType; -import org.springframework.data.cassandra.mapping.UserTypeResolver; import com.datastax.driver.core.KeyspaceMetadata; import com.datastax.driver.core.TableMetadata; @@ -41,7 +40,7 @@ import com.datastax.driver.core.UserType; /** * Unit tests for {@link CassandraPersistentEntitySchemaDropper}. - * + * * @author Mark Paluch. */ @SuppressWarnings("unchecked") @@ -62,12 +61,7 @@ public class CassandraPersistentEntitySchemaDropperUnitTests { @Before public void setUp() throws Exception { - context.setUserTypeResolver(new UserTypeResolver() { - @Override - public UserType resolveType(CqlIdentifier typeName) { - return metadata.getUserType(typeName.toCql()); - } - }); + context.setUserTypeResolver(typeName -> metadata.getUserType(typeName.toCql())); when(operations.getKeyspaceMetadata()).thenReturn(metadata); when(universetype.getTypeName()).thenReturn("universetype"); @@ -80,7 +74,7 @@ public class CassandraPersistentEntitySchemaDropperUnitTests { @Test // DATACASS-355 public void shouldDropTypes() throws Exception { - context.setInitialEntitySet(new HashSet>(Arrays.asList(MoonType.class, UniverseType.class))); + context.setInitialEntitySet(new HashSet<>(Arrays.asList(MoonType.class, UniverseType.class))); context.afterPropertiesSet(); when(metadata.getUserTypes()).thenReturn(Arrays.asList(universetype, moontype, planettype)); @@ -100,7 +94,7 @@ public class CassandraPersistentEntitySchemaDropperUnitTests { @Test // DATACASS-355 public void dropUserTypesShouldRetainUnusedTypes() { - context.setInitialEntitySet(new HashSet>(Arrays.asList(MoonType.class, UniverseType.class))); + context.setInitialEntitySet(new HashSet<>(Arrays.asList(MoonType.class, UniverseType.class))); context.afterPropertiesSet(); when(metadata.getUserTypes()).thenReturn(Arrays.asList(universetype, moontype, planettype)); diff --git a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/core/CassandraTemplateIntegrationTests.java b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/core/CassandraTemplateIntegrationTests.java index de044fdd3..e604c4ff9 100644 --- a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/core/CassandraTemplateIntegrationTests.java +++ b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/core/CassandraTemplateIntegrationTests.java @@ -37,7 +37,7 @@ import com.datastax.driver.core.utils.UUIDs; /** * Integration tests for {@link CassandraTemplate}. - * + * * @author Mark Paluch */ public class CassandraTemplateIntegrationTests extends AbstractKeyspaceCreatingIntegrationTest { @@ -175,7 +175,7 @@ public class CassandraTemplateIntegrationTests extends AbstractKeyspaceCreatingI template.insert(bookReference); - bookReference.setBookmarks(Collections. emptyList()); + bookReference.setBookmarks(Collections.emptyList()); template.update(bookReference); diff --git a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/mapping/BasicCassandraMappingContextUnitTests.java b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/mapping/BasicCassandraMappingContextUnitTests.java index e26f1594b..6a0b9bf68 100755 --- a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/mapping/BasicCassandraMappingContextUnitTests.java +++ b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/mapping/BasicCassandraMappingContextUnitTests.java @@ -389,13 +389,7 @@ public class BasicCassandraMappingContextUnitTests { final UserType myTypeMock = mock(UserType.class, "mappedudt"); when(myTypeMock.getTypeName()).thenReturn("mappedudt"); - mappingContext.setUserTypeResolver(new UserTypeResolver() { - - @Override - public UserType resolveType(CqlIdentifier typeName) { - return myTypeMock; - } - }); + mappingContext.setUserTypeResolver(typeName -> myTypeMock); mappingContext.getRequiredPersistentEntity(WithUdt.class); @@ -408,13 +402,7 @@ public class BasicCassandraMappingContextUnitTests { final UserType myTypeMock = mock(UserType.class, "mappedudt"); when(myTypeMock.getTypeName()).thenReturn("mappedudt"); - mappingContext.setUserTypeResolver(new UserTypeResolver() { - - @Override - public UserType resolveType(CqlIdentifier typeName) { - return myTypeMock; - } - }); + mappingContext.setUserTypeResolver(typeName -> myTypeMock); mappingContext.getRequiredPersistentEntity(MappedUdt.class); diff --git a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/mapping/BasicCassandraPersistentEntityOrderPropertiesUnitTests.java b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/mapping/BasicCassandraPersistentEntityOrderPropertiesUnitTests.java index d8085596e..347f1ee41 100755 --- a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/mapping/BasicCassandraPersistentEntityOrderPropertiesUnitTests.java +++ b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/mapping/BasicCassandraPersistentEntityOrderPropertiesUnitTests.java @@ -51,15 +51,9 @@ public class BasicCassandraPersistentEntityOrderPropertiesUnitTests { expected.add(entity.getRequiredPersistentProperty("key1")); expected.add(entity.getRequiredPersistentProperty("key2")); - final List actual = new LinkedList(); + final List actual = new LinkedList<>(); - entity.doWithProperties(new PropertyHandler() { - - @Override - public void doWithPersistentProperty(CassandraPersistentProperty persistentProperty) { - actual.add(persistentProperty); - } - }); + entity.doWithProperties((PropertyHandler) actual::add); assertThat(actual).isEqualTo(expected); @@ -70,20 +64,14 @@ public class BasicCassandraPersistentEntityOrderPropertiesUnitTests { CassandraPersistentEntity entity = mappingContext.getRequiredPersistentEntity(CompositeKeyEntity.class); - expected = new LinkedList(); + expected = new LinkedList<>(); expected.add(entity.getRequiredPersistentProperty("key")); expected.add(entity.getRequiredPersistentProperty("attribute")); expected.add(entity.getRequiredPersistentProperty("text")); - final List actual = new LinkedList(); + final List actual = new LinkedList<>(); - entity.doWithProperties(new PropertyHandler() { - - @Override - public void doWithPersistentProperty(CassandraPersistentProperty persistentProperty) { - actual.add(persistentProperty); - } - }); + entity.doWithProperties((PropertyHandler) actual::add); assertThat(actual).isEqualTo(expected); diff --git a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/mapping/BasicCassandraPersistentEntityUnitTests.java b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/mapping/BasicCassandraPersistentEntityUnitTests.java index fd0aab025..0d65cdaaa 100755 --- a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/mapping/BasicCassandraPersistentEntityUnitTests.java +++ b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/mapping/BasicCassandraPersistentEntityUnitTests.java @@ -49,7 +49,7 @@ public class BasicCassandraPersistentEntityUnitTests { @Test public void subclassInheritsAtDocumentAnnotation() { - BasicCassandraPersistentEntity entity = new BasicCassandraPersistentEntity( + BasicCassandraPersistentEntity entity = new BasicCassandraPersistentEntity<>( ClassTypeInformation.from(Notification.class)); assertThat(entity.getTableName().toCql()).isEqualTo("messages"); } @@ -57,7 +57,7 @@ public class BasicCassandraPersistentEntityUnitTests { @Test public void evaluatesSpELExpression() { - BasicCassandraPersistentEntity entity = new BasicCassandraPersistentEntity( + BasicCassandraPersistentEntity entity = new BasicCassandraPersistentEntity<>( ClassTypeInformation.from(Area.class)); entity.setApplicationContext(context); assertThat(entity.getTableName().toCql()).isEqualTo("a123"); @@ -72,7 +72,7 @@ public class BasicCassandraPersistentEntityUnitTests { when(context.getBean("tableNameHolderThingy")).thenReturn(bean); when(context.containsBean("tableNameHolderThingy")).thenReturn(true); - BasicCassandraPersistentEntity entity = new BasicCassandraPersistentEntity( + BasicCassandraPersistentEntity entity = new BasicCassandraPersistentEntity<>( ClassTypeInformation.from(UserLine.class)); entity.setApplicationContext(context); @@ -82,7 +82,7 @@ public class BasicCassandraPersistentEntityUnitTests { @Test public void setForceQuoteCallsSetTableName() { BasicCassandraPersistentEntity entitySpy = spy( - new BasicCassandraPersistentEntity(ClassTypeInformation.from(Message.class))); + new BasicCassandraPersistentEntity<>(ClassTypeInformation.from(Message.class))); entitySpy.setTableName(CqlIdentifier.cqlId("Messages", false)); @@ -98,7 +98,7 @@ public class BasicCassandraPersistentEntityUnitTests { @Test public void setForceQuoteDoesNothing() { BasicCassandraPersistentEntity entitySpy = spy( - new BasicCassandraPersistentEntity(ClassTypeInformation.from(Message.class))); + new BasicCassandraPersistentEntity<>(ClassTypeInformation.from(Message.class))); entitySpy.forceQuote = Optional.of(true); entitySpy.setForceQuote(true); @@ -111,7 +111,7 @@ public class BasicCassandraPersistentEntityUnitTests { @Test // DATACASS-172 public void isUserDefinedTypeShouldReturnFalse() { - BasicCassandraPersistentEntity entity = new BasicCassandraPersistentEntity( + BasicCassandraPersistentEntity entity = new BasicCassandraPersistentEntity<>( ClassTypeInformation.from(UserLine.class)); assertThat(entity.isUserDefinedType()).isFalse(); @@ -120,7 +120,7 @@ public class BasicCassandraPersistentEntityUnitTests { @Test // DATACASS-259 public void shouldConsiderComposedTableAnnotation() { - BasicCassandraPersistentEntity entity = new BasicCassandraPersistentEntity( + BasicCassandraPersistentEntity entity = new BasicCassandraPersistentEntity<>( ClassTypeInformation.from(TableWithComposedAnnotation.class)); assertThat(entity.getTableName()).isEqualTo(CqlIdentifier.cqlId("mytable", true)); @@ -129,7 +129,7 @@ public class BasicCassandraPersistentEntityUnitTests { @Test // DATACASS-259 public void shouldConsiderComposedPrimaryKeyClassAnnotation() { - BasicCassandraPersistentEntity entity = new BasicCassandraPersistentEntity( + BasicCassandraPersistentEntity entity = new BasicCassandraPersistentEntity<>( ClassTypeInformation.from(PrimaryKeyClassWithComposedAnnotation.class)); assertThat(entity.isCompositePrimaryKey()).isTrue(); diff --git a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/mapping/BasicCassandraPersistentPropertyUnitTests.java b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/mapping/BasicCassandraPersistentPropertyUnitTests.java index de9e6eae8..1d4b4bc77 100755 --- a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/mapping/BasicCassandraPersistentPropertyUnitTests.java +++ b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/mapping/BasicCassandraPersistentPropertyUnitTests.java @@ -103,7 +103,7 @@ public class BasicCassandraPersistentPropertyUnitTests { } private BasicCassandraPersistentEntity getEntity(Class type) { - return new BasicCassandraPersistentEntity(ClassTypeInformation.from(type)); + return new BasicCassandraPersistentEntity<>(ClassTypeInformation.from(type)); } static class Timeline { diff --git a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/mapping/CassandraCompositePrimaryKeyUnitTests.java b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/mapping/CassandraCompositePrimaryKeyUnitTests.java index d131a8897..4c87dfa92 100755 --- a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/mapping/CassandraCompositePrimaryKeyUnitTests.java +++ b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/mapping/CassandraCompositePrimaryKeyUnitTests.java @@ -119,10 +119,10 @@ public class CassandraCompositePrimaryKeyUnitTests { assertThat(property.isIdProperty()).isTrue(); assertThat(property.isCompositePrimaryKey()).isTrue(); - List expectedColumnNames = Arrays.asList(new CqlIdentifier[] { cqlId("z"), cqlId("a") }); + List expectedColumnNames = Arrays.asList(cqlId("z"), cqlId("a")); assertThat(expectedColumnNames.equals(property.getColumnNames())).isTrue(); - List actualColumnNames = new ArrayList(); + List actualColumnNames = new ArrayList<>(); List properties = property.getCompositePrimaryKeyProperties(); for (CassandraPersistentProperty p : properties) { actualColumnNames.addAll(p.getColumnNames()); diff --git a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/mapping/CassandraUserTypePersistentEntityUnitTests.java b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/mapping/CassandraUserTypePersistentEntityUnitTests.java index 18d3b4e9a..c12977165 100644 --- a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/mapping/CassandraUserTypePersistentEntityUnitTests.java +++ b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/mapping/CassandraUserTypePersistentEntityUnitTests.java @@ -32,7 +32,7 @@ import org.springframework.data.util.ClassTypeInformation; /** * Unit tests for {@link CassandraUserTypePersistentEntity}. - * + * * @author Mark Paluch */ @RunWith(MockitoJUnitRunner.class) @@ -85,7 +85,7 @@ public class CassandraUserTypePersistentEntityUnitTests { } private CassandraUserTypePersistentEntity getEntity(Class entityClass) { - return new CassandraUserTypePersistentEntity(ClassTypeInformation.from(entityClass), mappingContextMock, null, + return new CassandraUserTypePersistentEntity<>(ClassTypeInformation.from(entityClass), mappingContextMock, null, userTypeResolverMock); } diff --git a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/mapping/CompoundPrimaryKeyUnitTests.java b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/mapping/CompoundPrimaryKeyUnitTests.java index 3bb750000..6d1e55e5e 100755 --- a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/mapping/CompoundPrimaryKeyUnitTests.java +++ b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/mapping/CompoundPrimaryKeyUnitTests.java @@ -56,8 +56,8 @@ public class CompoundPrimaryKeyUnitTests { @Before public void setup() { - cpk = new BasicCassandraPersistentEntity(ClassTypeInformation.from(TimelineKey.class)); - entity = new BasicCassandraPersistentEntity(ClassTypeInformation.from(Timeline.class)); + cpk = new BasicCassandraPersistentEntity<>(ClassTypeInformation.from(TimelineKey.class)); + entity = new BasicCassandraPersistentEntity<>(ClassTypeInformation.from(Timeline.class)); } @Test diff --git a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/mapping/CreateTableSpecificationBasicCassandraMappingContextUnitTests.java b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/mapping/CreateTableSpecificationBasicCassandraMappingContextUnitTests.java index 2a46e0dfb..c5e9abc46 100755 --- a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/mapping/CreateTableSpecificationBasicCassandraMappingContextUnitTests.java +++ b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/mapping/CreateTableSpecificationBasicCassandraMappingContextUnitTests.java @@ -60,7 +60,7 @@ public class CreateTableSpecificationBasicCassandraMappingContextUnitTests { @Before public void setUp() throws Exception { - List> converters = new ArrayList>(); + List> converters = new ArrayList<>(); converters.add(new PersonReadConverter()); converters.add(new PersonWriteConverter()); @@ -252,23 +252,20 @@ public class CreateTableSpecificationBasicCassandraMappingContextUnitTests { final UserType species_udt = mock(UserType.class, "species_udt"); final UserType peeps_udt = mock(UserType.class, "peeps_udt"); - ctx.setUserTypeResolver(new UserTypeResolver() { - @Override - public UserType resolveType(CqlIdentifier typeName) { + ctx.setUserTypeResolver(typeName -> { - if (typeName.toCql().equals(human_udt.toString())) { - return human_udt; - } - - if (typeName.toCql().equals(species_udt.toString())) { - return species_udt; - } - - if (typeName.toCql().equals(peeps_udt.toString())) { - return peeps_udt; - } - return null; + if (typeName.toCql().equals(human_udt.toString())) { + return human_udt; } + + if (typeName.toCql().equals(species_udt.toString())) { + return species_udt; + } + + if (typeName.toCql().equals(peeps_udt.toString())) { + return peeps_udt; + } + return null; }); CreateTableSpecification specification = getCreateTableSpecificationFor(WithUdtFields.class); @@ -283,15 +280,12 @@ public class CreateTableSpecificationBasicCassandraMappingContextUnitTests { final UserType mappedUdt = mock(UserType.class, "mappedudt"); - ctx.setUserTypeResolver(new UserTypeResolver() { - @Override - public UserType resolveType(CqlIdentifier typeName) { + ctx.setUserTypeResolver(typeName -> { - if (typeName.toCql().equals(mappedUdt.toString())) { - return mappedUdt; - } - return null; + if (typeName.toCql().equals(mappedUdt.toString())) { + return mappedUdt; } + return null; }); CreateTableSpecification specification = getCreateTableSpecificationFor(WithMappedUdtFields.class); diff --git a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/mapping/ForceQuotedEntitiesSimpleUnitTests.java b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/mapping/ForceQuotedEntitiesSimpleUnitTests.java index 2f1eabcc1..0fb9dbb25 100755 --- a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/mapping/ForceQuotedEntitiesSimpleUnitTests.java +++ b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/mapping/ForceQuotedEntitiesSimpleUnitTests.java @@ -30,7 +30,7 @@ public class ForceQuotedEntitiesSimpleUnitTests { @Test public void testImplicitTableNameForceQuoted() { - BasicCassandraPersistentEntity entity = new BasicCassandraPersistentEntity( + BasicCassandraPersistentEntity entity = new BasicCassandraPersistentEntity<>( ClassTypeInformation.from(ImplicitTableNameForceQuoted.class)); assertThat(entity.getTableName().toCql()) @@ -45,7 +45,7 @@ public class ForceQuotedEntitiesSimpleUnitTests { @Test public void testExplicitTableNameForceQuoted() { - BasicCassandraPersistentEntity entity = new BasicCassandraPersistentEntity( + BasicCassandraPersistentEntity entity = new BasicCassandraPersistentEntity<>( ClassTypeInformation.from(ExplicitTableNameForceQuoted.class)); assertThat(entity.getTableName().toCql()).isEqualTo("\"" + EXPLICIT_TABLE_NAME + "\""); @@ -57,7 +57,7 @@ public class ForceQuotedEntitiesSimpleUnitTests { @Test public void testDefaultTableNameForceQuoted() { - BasicCassandraPersistentEntity entity = new BasicCassandraPersistentEntity( + BasicCassandraPersistentEntity entity = new BasicCassandraPersistentEntity<>( ClassTypeInformation.from(DefaultTableNameForceQuoted.class)); assertThat(entity.getTableName().toCql()) diff --git a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/mapping/multipackagescanning/MultipackageScanningUnitTests.java b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/mapping/multipackagescanning/MultipackageScanningUnitTests.java index 46d7471fe..92c2b1f05 100755 --- a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/mapping/multipackagescanning/MultipackageScanningUnitTests.java +++ b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/mapping/multipackagescanning/MultipackageScanningUnitTests.java @@ -19,6 +19,7 @@ import static org.assertj.core.api.Assertions.*; import java.util.Collection; import java.util.HashSet; +import java.util.stream.Collectors; import org.junit.Before; import org.junit.Test; @@ -53,10 +54,7 @@ public class MultipackageScanningUnitTests { Collection> entities = mapping.getPersistentEntities(); - Collection> types = new HashSet>(entities.size()); - for (CassandraPersistentEntity entity : entities) { - types.add(entity.getType()); - } + Collection> types = entities.stream().map(CassandraPersistentEntity::getType).collect(Collectors.toSet()); assertThat(types.contains(First.class)).isTrue(); assertThat(types.contains(Second.class)).isTrue(); diff --git a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/repository/query/CassandraParametersParameterAccessorUnitTests.java b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/repository/query/CassandraParametersParameterAccessorUnitTests.java index fbd43f1ea..b51344dee 100755 --- a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/repository/query/CassandraParametersParameterAccessorUnitTests.java +++ b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/repository/query/CassandraParametersParameterAccessorUnitTests.java @@ -55,7 +55,7 @@ public class CassandraParametersParameterAccessorUnitTests { Method method = PossibleRepository.class.getMethod("findByFirstname", String.class); CassandraParameterAccessor accessor = new CassandraParametersParameterAccessor(getCassandraQueryMethod(method), - new Object[] { "firstname" }); + "firstname"); assertThat(accessor.getDataType(0)).isEqualTo(DataType.varchar()); } @@ -65,7 +65,7 @@ public class CassandraParametersParameterAccessorUnitTests { Method method = PossibleRepository.class.getMethod("findByBpLocalDateTime", LocalDateTime.class); CassandraParameterAccessor accessor = new CassandraParametersParameterAccessor(getCassandraQueryMethod(method), - new Object[] { LocalDateTime.of(2000, 10, 11, 12, 13, 14) }); + LocalDateTime.of(2000, 10, 11, 12, 13, 14)); assertThat(accessor.getDataType(0)).isNull(); } @@ -75,7 +75,7 @@ public class CassandraParametersParameterAccessorUnitTests { Method method = PossibleRepository.class.getMethod("findByAnnotatedBpLocalDateTime", LocalDateTime.class); CassandraParameterAccessor accessor = new CassandraParametersParameterAccessor(getCassandraQueryMethod(method), - new Object[] { LocalDateTime.of(2000, 10, 11, 12, 13, 14) }); + LocalDateTime.of(2000, 10, 11, 12, 13, 14)); assertThat(accessor.getDataType(0)).isEqualTo(DataType.date()); } @@ -85,7 +85,7 @@ public class CassandraParametersParameterAccessorUnitTests { Method method = PossibleRepository.class.getMethod("findByAnnotatedObject", Object.class); CassandraParameterAccessor accessor = new CassandraParametersParameterAccessor(getCassandraQueryMethod(method), - new Object[] { "" }); + ""); assertThat(accessor.getDataType(0)).isEqualTo(DataType.date()); } @@ -95,7 +95,7 @@ public class CassandraParametersParameterAccessorUnitTests { Method method = PossibleRepository.class.getMethod("findByAnnotatedObject", Object.class); CassandraParameterAccessor accessor = new CassandraParametersParameterAccessor(getCassandraQueryMethod(method), - new Object[] { "" }); + ""); assertThat(accessor.getDataType(0)).isEqualTo(DataType.date()); } diff --git a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/repository/query/ParameterBindingParserUnitTests.java b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/repository/query/ParameterBindingParserUnitTests.java index f114988b7..4098fdb5f 100644 --- a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/repository/query/ParameterBindingParserUnitTests.java +++ b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/repository/query/ParameterBindingParserUnitTests.java @@ -48,7 +48,7 @@ public class ParameterBindingParserUnitTests { public void parseWithStaticParameters() { String query = "SELECT * FROM hello_world WHERE a = 1 AND b = {'list'} AND c = {'key':'value'}"; - List bindings = new ArrayList(); + List bindings = new ArrayList<>(); String transformed = ParameterBindingParser.INSTANCE.parseAndCollectParameterBindingsFromQueryIntoBindings(query, bindings); @@ -61,7 +61,7 @@ public class ParameterBindingParserUnitTests { public void parseWithPositionalParameters() { String query = "SELECT * FROM hello_world WHERE a = ?0 and b = ?13"; - List bindings = new ArrayList(); + List bindings = new ArrayList<>(); String transformed = ParameterBindingParser.INSTANCE.parseAndCollectParameterBindingsFromQueryIntoBindings(query, bindings); @@ -77,7 +77,7 @@ public class ParameterBindingParserUnitTests { public void parseWithNamedParameters() { String query = "SELECT * FROM hello_world WHERE a = :hello and b = :world"; - List bindings = new ArrayList(); + List bindings = new ArrayList<>(); String transformed = ParameterBindingParser.INSTANCE.parseAndCollectParameterBindingsFromQueryIntoBindings(query, bindings); @@ -90,7 +90,7 @@ public class ParameterBindingParserUnitTests { public void parseWithIndexExpressionParameters() { String query = "SELECT * FROM hello_world WHERE a = ?#{[0]} and b = ?#{[2]}"; - List bindings = new ArrayList(); + List bindings = new ArrayList<>(); String transformed = ParameterBindingParser.INSTANCE.parseAndCollectParameterBindingsFromQueryIntoBindings(query, bindings); @@ -103,7 +103,7 @@ public class ParameterBindingParserUnitTests { public void parseWithNameExpressionParameters() { String query = "SELECT * FROM hello_world WHERE a = :#{#a} and b = :#{#b}"; - List bindings = new ArrayList(); + List bindings = new ArrayList<>(); String transformed = ParameterBindingParser.INSTANCE.parseAndCollectParameterBindingsFromQueryIntoBindings(query, bindings); @@ -116,7 +116,7 @@ public class ParameterBindingParserUnitTests { public void parseWithMixedParameters() { String query = "SELECT * FROM hello_world WHERE (a = ?1 and b = :name) and c = (:#{#a}) and (d = ?#{[1]})"; - List bindings = new ArrayList(); + List bindings = new ArrayList<>(); String transformed = ParameterBindingParser.INSTANCE.parseAndCollectParameterBindingsFromQueryIntoBindings(query, bindings); diff --git a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/repository/query/PartTreeCassandraQueryUnitTests.java b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/repository/query/PartTreeCassandraQueryUnitTests.java index e211e2160..38cda85f2 100644 --- a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/repository/query/PartTreeCassandraQueryUnitTests.java +++ b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/repository/query/PartTreeCassandraQueryUnitTests.java @@ -76,7 +76,7 @@ public class PartTreeCassandraQueryUnitTests { when(mockCassandraOperations.getConverter()).thenReturn(converter); when(udtValueMock.getType()).thenReturn(userTypeMock); - when(userTypeMock.iterator()).thenReturn(Collections. emptyIterator()); + when(userTypeMock.iterator()).thenReturn(Collections.emptyIterator()); } @Test // DATACASS-7 diff --git a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/repository/query/StringBasedCassandraQueryUnitTests.java b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/repository/query/StringBasedCassandraQueryUnitTests.java index cdac3a559..2f77fcfa0 100755 --- a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/repository/query/StringBasedCassandraQueryUnitTests.java +++ b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/repository/query/StringBasedCassandraQueryUnitTests.java @@ -208,7 +208,7 @@ public class StringBasedCassandraQueryUnitTests { StringBasedCassandraQuery cassandraQuery = getQueryMethod("findByLastNameIn", Collection.class); CassandraParametersParameterAccessor accessor = new CassandraParametersParameterAccessor( - cassandraQuery.getQueryMethod(), new HashSet(Arrays.asList("White", "Heisenberg"))); + cassandraQuery.getQueryMethod(), new HashSet<>(Arrays.asList("White", "Heisenberg"))); String actual = cassandraQuery.createQuery(accessor); diff --git a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/repository/support/BasicMapIdUnitTests.java b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/repository/support/BasicMapIdUnitTests.java index 784edbf61..de4034aa4 100755 --- a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/repository/support/BasicMapIdUnitTests.java +++ b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/repository/support/BasicMapIdUnitTests.java @@ -32,7 +32,7 @@ import org.junit.Test; public class BasicMapIdUnitTests { @Test public void testMapConstructor() { - Map map = new HashMap(); + Map map = new HashMap<>(); map.put("field1", "value1"); map.put("field2", 2); diff --git a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/repository/support/SimpleReactiveCassandraRepositoryIntegrationTests.java b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/repository/support/SimpleReactiveCassandraRepositoryIntegrationTests.java index e24967f08..d5c408ea7 100644 --- a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/repository/support/SimpleReactiveCassandraRepositoryIntegrationTests.java +++ b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/repository/support/SimpleReactiveCassandraRepositoryIntegrationTests.java @@ -44,7 +44,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * Integration tests for {@link SimpleReactiveCassandraRepository}. - * + * * @author Mark Paluch */ @RunWith(SpringJUnit4ClassRunner.class) @@ -382,5 +382,5 @@ public class SimpleReactiveCassandraRepositoryIntegrationTests extends AbstractK verificationSubscriber.await().assertComplete().assertNoValues(); } - static interface PersonRepostitory extends ReactiveCassandraRepository {} + interface PersonRepostitory extends ReactiveCassandraRepository {} } diff --git a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/test/integration/collections/CollectionsRowValueProviderIntegrationTests.java b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/test/integration/collections/CollectionsRowValueProviderIntegrationTests.java index 888b1f1e6..b77479a52 100755 --- a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/test/integration/collections/CollectionsRowValueProviderIntegrationTests.java +++ b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/test/integration/collections/CollectionsRowValueProviderIntegrationTests.java @@ -72,7 +72,7 @@ public class CollectionsRowValueProviderIntegrationTests extends AbstractKeyspac b1.setSaleDate(new Date()); b1.setInStock(true); - Map checkOutMap = new HashMap(); + Map checkOutMap = new HashMap<>(); checkOutMap.put("dwebb", 50); checkOutMap.put("madams", 100); checkOutMap.put("jmcpeek", 150); @@ -102,13 +102,13 @@ public class CollectionsRowValueProviderIntegrationTests extends AbstractKeyspac b1.setSaleDate(new Date()); b1.setInStock(true); - Set refs = new HashSet(); + Set refs = new HashSet<>(); refs.add("Spring Data by O'Reilly"); refs.add("Spring by Example"); refs.add("Spring Recipies"); b1.setReferences(refs); - List marks = new LinkedList(); + List marks = new LinkedList<>(); marks.add(13); marks.add(52); marks.add(144); diff --git a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/test/integration/forcequote/compositeprimarykey/CompositeKeyCrudIntegrationTests.java b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/test/integration/forcequote/compositeprimarykey/CompositeKeyCrudIntegrationTests.java index 1f0ba71ed..2633a92b0 100755 --- a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/test/integration/forcequote/compositeprimarykey/CompositeKeyCrudIntegrationTests.java +++ b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/test/integration/forcequote/compositeprimarykey/CompositeKeyCrudIntegrationTests.java @@ -53,10 +53,10 @@ public class CompositeKeyCrudIntegrationTests extends AbstractKeyspaceCreatingIn SchemaTestUtils.potentiallyCreateTableFor(CorrelationEntity.class, operations); SchemaTestUtils.truncate(CorrelationEntity.class, operations); - Map map1 = new HashMap(2); + Map map1 = new HashMap<>(2); map1.put("v", "1"); map1.put("labels", "1,2,3"); - Map map2 = new HashMap(2); + Map map2 = new HashMap<>(2); map2.put("v", "1"); map2.put("labels", "4,5,6"); diff --git a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/test/integration/forcequote/compositeprimarykey/entity/CorrelationEntity.java b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/test/integration/forcequote/compositeprimarykey/entity/CorrelationEntity.java index e4ee22944..fe19a06c6 100644 --- a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/test/integration/forcequote/compositeprimarykey/entity/CorrelationEntity.java +++ b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/test/integration/forcequote/compositeprimarykey/entity/CorrelationEntity.java @@ -134,10 +134,7 @@ public class CorrelationEntity { return false; if (!type.equals(that.type)) return false; - if (!value.equals(that.value)) - return false; - - return true; + return value.equals(that.value); } @Override @@ -195,10 +192,7 @@ public class CorrelationEntity { if (extra != null ? !extra.equals(that.extra) : that.extra != null) return false; - if (!identityEntity.equals(that.identityEntity)) - return false; - - return true; + return identityEntity.equals(that.identityEntity); } @Override diff --git a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/test/integration/repository/simple/UserRepositoryIntegrationTests.java b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/test/integration/repository/simple/UserRepositoryIntegrationTests.java index a22c3fc98..ad370d19e 100755 --- a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/test/integration/repository/simple/UserRepositoryIntegrationTests.java +++ b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/test/integration/repository/simple/UserRepositoryIntegrationTests.java @@ -169,7 +169,7 @@ public class UserRepositoryIntegrationTests { public void save() { tom.setPassword(null); - tom.setFriends(Collections. emptySet()); + tom.setFriends(Collections.emptySet()); repository.save(tom); diff --git a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/test/integration/simpletons/BookCondition.java b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/test/integration/simpletons/BookCondition.java index adc47b5f7..b86101b4c 100644 --- a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/test/integration/simpletons/BookCondition.java +++ b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/test/integration/simpletons/BookCondition.java @@ -19,5 +19,5 @@ package org.springframework.data.cassandra.test.integration.simpletons; * @author Mark Paluch */ public enum BookCondition { - NEW, USED; + NEW, USED } diff --git a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/test/integration/support/AbstractSpringDataEmbeddedCassandraIntegrationTest.java b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/test/integration/support/AbstractSpringDataEmbeddedCassandraIntegrationTest.java index dab42e6e9..e2538191c 100755 --- a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/test/integration/support/AbstractSpringDataEmbeddedCassandraIntegrationTest.java +++ b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/test/integration/support/AbstractSpringDataEmbeddedCassandraIntegrationTest.java @@ -15,6 +15,8 @@ */ package org.springframework.data.cassandra.test.integration.support; +import java.util.stream.Stream; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -39,12 +41,9 @@ public abstract class AbstractSpringDataEmbeddedCassandraIntegrationTest */ public void deleteAllEntities() { - for (CassandraPersistentEntity entity : template.getConverter().getMappingContext().getTableEntities()) { - if (entity.getType().isInterface()) { - continue; - } + Stream> stream = template.getConverter().getMappingContext().getTableEntities() + .stream(); - template.truncate(entity.getType()); - } + stream.map(CassandraPersistentEntity::getType).filter(type -> !type.isInterface()).forEach(template::truncate); } } diff --git a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/test/integration/support/IntegrationTestConfig.java b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/test/integration/support/IntegrationTestConfig.java index ef03bbe06..fc44f3013 100644 --- a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/test/integration/support/IntegrationTestConfig.java +++ b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/test/integration/support/IntegrationTestConfig.java @@ -17,7 +17,7 @@ package org.springframework.data.cassandra.test.integration.support; import static org.springframework.cassandra.core.keyspace.CreateKeyspaceSpecification.*; -import java.util.Arrays; +import java.util.Collections; import java.util.List; import org.springframework.cassandra.core.keyspace.CreateKeyspaceSpecification; @@ -77,11 +77,11 @@ public class IntegrationTestConfig extends AbstractReactiveCassandraConfiguratio @Override protected List getKeyspaceCreations() { - return Arrays.asList(createKeyspace().name(getKeyspaceName()).withSimpleReplication()); + return Collections.singletonList(createKeyspace().name(getKeyspaceName()).withSimpleReplication()); } @Override protected List getKeyspaceDrops() { - return Arrays.asList(DropKeyspaceSpecification.dropKeyspace().name(getKeyspaceName())); + return Collections.singletonList(DropKeyspaceSpecification.dropKeyspace().name(getKeyspaceName())); } } diff --git a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/test/integration/support/SchemaTestUtils.java b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/test/integration/support/SchemaTestUtils.java index 269df540f..95c2a1985 100644 --- a/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/test/integration/support/SchemaTestUtils.java +++ b/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/test/integration/support/SchemaTestUtils.java @@ -18,26 +18,23 @@ package org.springframework.data.cassandra.test.integration.support; import org.springframework.cassandra.core.SessionCallback; import org.springframework.cassandra.core.cql.generator.CreateTableCqlGenerator; import org.springframework.cassandra.core.keyspace.CreateTableSpecification; -import org.springframework.dao.DataAccessException; import org.springframework.data.cassandra.core.CassandraOperations; import org.springframework.data.cassandra.mapping.CassandraMappingContext; import org.springframework.data.cassandra.mapping.CassandraPersistentEntity; import com.datastax.driver.core.KeyspaceMetadata; -import com.datastax.driver.core.Session; -import com.datastax.driver.core.exceptions.DriverException; /** * {@link SchemaTestUtils} is a collection of reflection-based utility methods for use in unit and integration testing * scenarios. - * + * * @author Mark Paluch */ public class SchemaTestUtils { /** * Create a table for {@code entityClass} if it not exists. - * + * * @param entityClass must not be {@literal null}. * @param operations must not be {@literal null}. */ @@ -46,23 +43,20 @@ public class SchemaTestUtils { CassandraMappingContext mappingContext = operations.getConverter().getMappingContext(); CassandraPersistentEntity persistentEntity = mappingContext.getRequiredPersistentEntity(entityClass); - operations.getCqlOperations().execute(new SessionCallback() { - @Override - public Object doInSession(Session session) throws DriverException, DataAccessException { + operations.getCqlOperations().execute((SessionCallback) session -> { - KeyspaceMetadata keyspace = session.getCluster().getMetadata().getKeyspace(session.getLoggedKeyspace()); - if (keyspace.getTable(persistentEntity.getTableName().toCql()) == null) { - CreateTableSpecification tableSpecification = mappingContext.getCreateTableSpecificationFor(persistentEntity); - operations.getCqlOperations().execute(new CreateTableCqlGenerator(tableSpecification).toCql()); - } - return null; + KeyspaceMetadata keyspace = session.getCluster().getMetadata().getKeyspace(session.getLoggedKeyspace()); + if (keyspace.getTable(persistentEntity.getTableName().toCql()) == null) { + CreateTableSpecification tableSpecification = mappingContext.getCreateTableSpecificationFor(persistentEntity); + operations.getCqlOperations().execute(new CreateTableCqlGenerator(tableSpecification).toCql()); } + return null; }); } /** * Truncate table for {@code entityClass}. - * + * * @param entityClass must not be {@literal null}. * @param operations must not be {@literal null}. */