Upgrade to Spring Data Neumann-M1

Closes gh-19588
pull/19681/head
Stephane Nicoll 5 years ago
commit 42a06060f8

@ -1,5 +1,5 @@
/*
* Copyright 2012-2019 the original author or authors.
* Copyright 2012-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -18,7 +18,7 @@ package org.springframework.boot.actuate.autoconfigure.cassandra;
import java.util.Map;
import com.datastax.driver.core.Cluster;
import com.datastax.oss.driver.api.core.CqlSession;
import org.springframework.boot.actuate.autoconfigure.health.CompositeHealthContributorConfiguration;
import org.springframework.boot.actuate.autoconfigure.health.ConditionalOnEnabledHealthIndicator;
@ -44,7 +44,7 @@ import org.springframework.data.cassandra.core.CassandraOperations;
* @since 2.1.0
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass({ Cluster.class, CassandraOperations.class })
@ConditionalOnClass({ CqlSession.class, CassandraOperations.class })
@ConditionalOnBean(CassandraOperations.class)
@ConditionalOnEnabledHealthIndicator("cassandra")
@AutoConfigureAfter({ CassandraAutoConfiguration.class, CassandraDataAutoConfiguration.class,

@ -1,5 +1,5 @@
/*
* Copyright 2012-2019 the original author or authors.
* Copyright 2012-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -17,7 +17,7 @@ package org.springframework.boot.actuate.autoconfigure.cassandra;
import java.util.Map;
import com.datastax.driver.core.Cluster;
import com.datastax.oss.driver.api.core.CqlSession;
import reactor.core.publisher.Flux;
import org.springframework.boot.actuate.autoconfigure.health.CompositeReactiveHealthContributorConfiguration;
@ -43,7 +43,7 @@ import org.springframework.data.cassandra.core.ReactiveCassandraOperations;
* @since 2.1.0
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass({ Cluster.class, ReactiveCassandraOperations.class, Flux.class })
@ConditionalOnClass({ CqlSession.class, ReactiveCassandraOperations.class, Flux.class })
@ConditionalOnBean(ReactiveCassandraOperations.class)
@ConditionalOnEnabledHealthIndicator("cassandra")
@AutoConfigureAfter(CassandraReactiveDataAutoConfiguration.class)

@ -1,5 +1,5 @@
/*
* Copyright 2012-2019 the original author or authors.
* Copyright 2012-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -16,9 +16,8 @@
package org.springframework.boot.actuate.cassandra;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.querybuilder.QueryBuilder;
import com.datastax.driver.core.querybuilder.Select;
import com.datastax.oss.driver.api.core.cql.ResultSet;
import com.datastax.oss.driver.api.core.cql.SimpleStatement;
import org.springframework.boot.actuate.health.AbstractHealthIndicator;
import org.springframework.boot.actuate.health.Health;
@ -53,9 +52,9 @@ public class CassandraHealthIndicator extends AbstractHealthIndicator {
@Override
protected void doHealthCheck(Health.Builder builder) throws Exception {
Select select = QueryBuilder.select("release_version").from("system", "local");
SimpleStatement select = SimpleStatement.newInstance("SELECT release_version FROM system.local");
ResultSet results = this.cassandraOperations.getCqlOperations().queryForResultSet(select);
if (results.isExhausted()) {
if (results.isFullyFetched()) {
builder.up();
return;
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2019 the original author or authors.
* Copyright 2012-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -15,8 +15,7 @@
*/
package org.springframework.boot.actuate.cassandra;
import com.datastax.driver.core.querybuilder.QueryBuilder;
import com.datastax.driver.core.querybuilder.Select;
import com.datastax.oss.driver.api.core.cql.SimpleStatement;
import reactor.core.publisher.Mono;
import org.springframework.boot.actuate.health.AbstractReactiveHealthIndicator;
@ -47,7 +46,7 @@ public class CassandraReactiveHealthIndicator extends AbstractReactiveHealthIndi
@Override
protected Mono<Health> doHealthCheck(Health.Builder builder) {
Select select = QueryBuilder.select("release_version").from("system", "local");
SimpleStatement select = SimpleStatement.newInstance("SELECT release_version FROM system.local");
return this.reactiveCassandraOperations.getReactiveCqlOperations().queryForObject(select, String.class)
.map((version) -> builder.up().withDetail("version", version).build()).single();
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2019 the original author or authors.
* Copyright 2012-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -16,9 +16,9 @@
package org.springframework.boot.actuate.cassandra;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Row;
import com.datastax.driver.core.querybuilder.Select;
import com.datastax.oss.driver.api.core.cql.ResultSet;
import com.datastax.oss.driver.api.core.cql.Row;
import com.datastax.oss.driver.api.core.cql.SimpleStatement;
import org.junit.jupiter.api.Test;
import org.springframework.boot.actuate.health.Health;
@ -51,8 +51,8 @@ class CassandraHealthIndicatorTests {
ResultSet resultSet = mock(ResultSet.class);
CassandraHealthIndicator healthIndicator = new CassandraHealthIndicator(cassandraOperations);
given(cassandraOperations.getCqlOperations()).willReturn(cqlOperations);
given(cqlOperations.queryForResultSet(any(Select.class))).willReturn(resultSet);
given(resultSet.isExhausted()).willReturn(true);
given(cqlOperations.queryForResultSet(any(SimpleStatement.class))).willReturn(resultSet);
given(resultSet.isFullyFetched()).willReturn(true);
Health health = healthIndicator.health();
assertThat(health.getStatus()).isEqualTo(Status.UP);
}
@ -65,8 +65,8 @@ class CassandraHealthIndicatorTests {
Row row = mock(Row.class);
CassandraHealthIndicator healthIndicator = new CassandraHealthIndicator(cassandraOperations);
given(cassandraOperations.getCqlOperations()).willReturn(cqlOperations);
given(cqlOperations.queryForResultSet(any(Select.class))).willReturn(resultSet);
given(resultSet.isExhausted()).willReturn(false);
given(cqlOperations.queryForResultSet(any(SimpleStatement.class))).willReturn(resultSet);
given(resultSet.isFullyFetched()).willReturn(false);
given(resultSet.one()).willReturn(row);
String expectedVersion = "1.0.0";
given(row.getString(0)).willReturn(expectedVersion);

@ -1,5 +1,5 @@
/*
* Copyright 2012-2019 the original author or authors.
* Copyright 2012-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -15,7 +15,7 @@
*/
package org.springframework.boot.actuate.cassandra;
import com.datastax.driver.core.querybuilder.Select;
import com.datastax.oss.driver.api.core.cql.SimpleStatement;
import org.junit.jupiter.api.Test;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
@ -42,7 +42,8 @@ class CassandraReactiveHealthIndicatorTests {
@Test
void testCassandraIsUp() {
ReactiveCqlOperations reactiveCqlOperations = mock(ReactiveCqlOperations.class);
given(reactiveCqlOperations.queryForObject(any(Select.class), eq(String.class))).willReturn(Mono.just("6.0.0"));
given(reactiveCqlOperations.queryForObject(any(SimpleStatement.class), eq(String.class)))
.willReturn(Mono.just("6.0.0"));
ReactiveCassandraOperations reactiveCassandraOperations = mock(ReactiveCassandraOperations.class);
given(reactiveCassandraOperations.getReactiveCqlOperations()).willReturn(reactiveCqlOperations);

@ -1,5 +1,5 @@
/*
* Copyright 2012-2019 the original author or authors.
* Copyright 2012-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -16,12 +16,24 @@
package org.springframework.boot.autoconfigure.cassandra;
import java.security.NoSuchAlgorithmException;
import java.time.Duration;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.PoolingOptions;
import com.datastax.driver.core.QueryOptions;
import com.datastax.driver.core.SocketOptions;
import javax.net.ssl.SSLContext;
import com.datastax.oss.driver.api.core.CqlSession;
import com.datastax.oss.driver.api.core.CqlSessionBuilder;
import com.datastax.oss.driver.api.core.config.DefaultDriverOption;
import com.datastax.oss.driver.api.core.config.DriverConfigLoader;
import com.datastax.oss.driver.api.core.config.DriverOption;
import com.datastax.oss.driver.api.core.config.ProgrammaticDriverConfigLoaderBuilder;
import com.datastax.oss.driver.internal.core.config.typesafe.DefaultDriverConfigLoader;
import com.datastax.oss.driver.internal.core.config.typesafe.DefaultProgrammaticDriverConfigLoaderBuilder;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
@ -31,7 +43,7 @@ import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.boot.context.properties.PropertyMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import org.springframework.context.annotation.Lazy;
/**
* {@link EnableAutoConfiguration Auto-configuration} for Cassandra.
@ -44,64 +56,131 @@ import org.springframework.util.StringUtils;
* @since 1.3.0
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass({ Cluster.class })
@ConditionalOnClass({ CqlSession.class })
@EnableConfigurationProperties(CassandraProperties.class)
public class CassandraAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public Cluster cassandraCluster(CassandraProperties properties,
ObjectProvider<ClusterBuilderCustomizer> builderCustomizers,
ObjectProvider<ClusterFactory> clusterFactory) {
@Lazy
public CqlSession cqlSession(CqlSessionBuilder cqlSessionBuilder) {
return cqlSessionBuilder.build();
}
@Bean
@ConditionalOnMissingBean
public CqlSessionBuilder cqlSessionBuilder(CassandraProperties properties, DriverConfigLoader driverConfigLoader,
ObjectProvider<CqlSessionBuilderCustomizer> builderCustomizers) {
CqlSessionBuilder builder = CqlSession.builder().withConfigLoader(driverConfigLoader);
configureSsl(properties, builder);
builder.withKeyspace(properties.getKeyspaceName());
builderCustomizers.orderedStream().forEach((customizer) -> customizer.customize(builder));
return builder;
}
private void configureSsl(CassandraProperties properties, CqlSessionBuilder builder) {
if (properties.isSsl()) {
try {
builder.withSslContext(SSLContext.getDefault());
}
catch (NoSuchAlgorithmException ex) {
throw new IllegalStateException("Could not setup SSL default context for Cassandra", ex);
}
}
}
@Bean
@ConditionalOnMissingBean
public DriverConfigLoader driverConfigLoader(CassandraProperties properties,
ObjectProvider<DriverConfigLoaderBuilderCustomizer> builderCustomizers) {
ProgrammaticDriverConfigLoaderBuilder builder = new DefaultProgrammaticDriverConfigLoaderBuilder(
() -> cassandraConfiguration(properties), DefaultDriverConfigLoader.DEFAULT_ROOT_PATH);
builderCustomizers.orderedStream().forEach((customizer) -> customizer.customizer(builder));
return builder.build();
}
private Config cassandraConfiguration(CassandraProperties properties) {
CassandraDriverOptions options = new CassandraDriverOptions();
PropertyMapper map = PropertyMapper.get();
Cluster.Builder builder = Cluster.builder().withClusterName(properties.getClusterName())
.withPort(properties.getPort());
map.from(properties.getSessionName()).whenHasText()
.to((sessionName) -> options.add(DefaultDriverOption.SESSION_NAME, sessionName));
map.from(properties::getUsername).whenNonNull()
.to((username) -> builder.withCredentials(username, properties.getPassword()));
map.from(properties::getCompression).whenNonNull().to(builder::withCompression);
QueryOptions queryOptions = getQueryOptions(properties);
map.from(queryOptions).to(builder::withQueryOptions);
SocketOptions socketOptions = getSocketOptions(properties);
map.from(socketOptions).to(builder::withSocketOptions);
map.from(properties::isSsl).whenTrue().toCall(builder::withSSL);
PoolingOptions poolingOptions = getPoolingOptions(properties);
map.from(poolingOptions).to(builder::withPoolingOptions);
map.from(properties::getContactPoints).as(StringUtils::toStringArray).to(builder::addContactPoints);
map.from(properties::isJmxEnabled).whenFalse().toCall(builder::withoutJMXReporting);
builderCustomizers.orderedStream().forEach((customizer) -> customizer.customize(builder));
return clusterFactory.getIfAvailable(() -> Cluster::buildFrom).create(builder);
.to((username) -> options.add(DefaultDriverOption.AUTH_PROVIDER_USER_NAME, username)
.add(DefaultDriverOption.AUTH_PROVIDER_PASSWORD, properties.getPassword()));
map.from(properties::getCompression).whenNonNull()
.to((compression) -> options.add(DefaultDriverOption.PROTOCOL_COMPRESSION, compression));
mapQueryOptions(properties, options);
mapSocketOptions(properties, options);
mapPoolingOptions(properties, options);
map.from(properties::getContactPoints)
.to((contactPoints) -> options.add(DefaultDriverOption.CONTACT_POINTS, contactPoints));
ConfigFactory.invalidateCaches();
return ConfigFactory.defaultOverrides().withFallback(options.build())
.withFallback(ConfigFactory.defaultReference()).resolve();
}
private QueryOptions getQueryOptions(CassandraProperties properties) {
private void mapQueryOptions(CassandraProperties properties, CassandraDriverOptions options) {
PropertyMapper map = PropertyMapper.get();
QueryOptions options = new QueryOptions();
map.from(properties::getConsistencyLevel).whenNonNull().to(options::setConsistencyLevel);
map.from(properties::getSerialConsistencyLevel).whenNonNull().to(options::setSerialConsistencyLevel);
map.from(properties::getFetchSize).to(options::setFetchSize);
return options;
map.from(properties::getConsistencyLevel).whenNonNull()
.to(((consistency) -> options.add(DefaultDriverOption.REQUEST_CONSISTENCY, consistency)));
map.from(properties::getSerialConsistencyLevel).whenNonNull().to(
(serialConsistency) -> options.add(DefaultDriverOption.REQUEST_SERIAL_CONSISTENCY, serialConsistency));
map.from(properties::getPageSize)
.to((pageSize) -> options.add(DefaultDriverOption.REQUEST_PAGE_SIZE, pageSize));
}
private SocketOptions getSocketOptions(CassandraProperties properties) {
private void mapSocketOptions(CassandraProperties properties, CassandraDriverOptions options) {
PropertyMapper map = PropertyMapper.get();
SocketOptions options = new SocketOptions();
map.from(properties::getConnectTimeout).whenNonNull().asInt(Duration::toMillis)
.to(options::setConnectTimeoutMillis);
map.from(properties::getReadTimeout).whenNonNull().asInt(Duration::toMillis).to(options::setReadTimeoutMillis);
return options;
.to((connectTimeout) -> options.add(DefaultDriverOption.CONNECTION_INIT_QUERY_TIMEOUT, connectTimeout));
map.from(properties::getReadTimeout).whenNonNull().asInt(Duration::toMillis)
.to((readTimeout) -> options.add(DefaultDriverOption.REQUEST_TIMEOUT, readTimeout));
}
private PoolingOptions getPoolingOptions(CassandraProperties properties) {
private void mapPoolingOptions(CassandraProperties properties, CassandraDriverOptions options) {
PropertyMapper map = PropertyMapper.get();
CassandraProperties.Pool poolProperties = properties.getPool();
PoolingOptions options = new PoolingOptions();
map.from(poolProperties::getIdleTimeout).whenNonNull().asInt(Duration::getSeconds)
.to(options::setIdleTimeoutSeconds);
map.from(poolProperties::getPoolTimeout).whenNonNull().asInt(Duration::toMillis)
.to(options::setPoolTimeoutMillis);
.to((idleTimeout) -> options.add(DefaultDriverOption.HEARTBEAT_TIMEOUT, idleTimeout));
map.from(poolProperties::getHeartbeatInterval).whenNonNull().asInt(Duration::getSeconds)
.to(options::setHeartbeatIntervalSeconds);
map.from(poolProperties::getMaxQueueSize).to(options::setMaxQueueSize);
return options;
.to((heartBeatInterval) -> options.add(DefaultDriverOption.HEARTBEAT_INTERVAL, heartBeatInterval));
map.from(poolProperties::getMaxQueueSize)
.to((maxQueueSize) -> options.add(DefaultDriverOption.REQUEST_THROTTLER_MAX_QUEUE_SIZE, maxQueueSize));
}
private static class CassandraDriverOptions {
private final Map<String, String> options = new LinkedHashMap<>();
private CassandraDriverOptions add(DriverOption option, String value) {
String key = createKeyFor(option);
this.options.put(key, value);
return this;
}
private CassandraDriverOptions add(DriverOption option, int value) {
return add(option, String.valueOf(value));
}
private CassandraDriverOptions add(DriverOption option, Enum<?> value) {
return add(option, value.name());
}
private CassandraDriverOptions add(DriverOption option, List<String> values) {
for (int i = 0; i < values.size(); i++) {
this.options.put(String.format("%s.%s", createKeyFor(option), i), values.get(i));
}
return this;
}
private Config build() {
return ConfigFactory.parseMap(this.options, "Environment");
}
private static String createKeyFor(DriverOption option) {
return String.format("%s.%s", DefaultDriverConfigLoader.DEFAULT_ROOT_PATH, option.getPath());
}
}
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2019 the original author or authors.
* Copyright 2012-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -22,12 +22,10 @@ import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import com.datastax.driver.core.ConsistencyLevel;
import com.datastax.driver.core.ProtocolOptions;
import com.datastax.driver.core.ProtocolOptions.Compression;
import com.datastax.driver.core.QueryOptions;
import com.datastax.oss.driver.api.core.DefaultConsistencyLevel;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.DeprecatedConfigurationProperty;
import org.springframework.boot.convert.DurationUnit;
/**
@ -48,19 +46,14 @@ public class CassandraProperties {
private String keyspaceName;
/**
* Name of the Cassandra cluster.
* Name of the Cassandra session.
*/
private String clusterName;
private String sessionName;
/**
* Cluster node addresses.
* Cluster node addresses in the form 'host:port'.
*/
private final List<String> contactPoints = new ArrayList<>(Collections.singleton("localhost"));
/**
* Port of the Cassandra server.
*/
private int port = ProtocolOptions.DEFAULT_PORT;
private final List<String> contactPoints = new ArrayList<>(Collections.singleton("127.0.0.1:9042"));
/**
* Login user of the server.
@ -80,17 +73,17 @@ public class CassandraProperties {
/**
* Queries consistency level.
*/
private ConsistencyLevel consistencyLevel;
private DefaultConsistencyLevel consistencyLevel;
/**
* Queries serial consistency level.
*/
private ConsistencyLevel serialConsistencyLevel;
private DefaultConsistencyLevel serialConsistencyLevel;
/**
* Queries default fetch size.
* Queries default page size.
*/
private int fetchSize = QueryOptions.DEFAULT_FETCH_SIZE;
private int pageSize = 5000;
/**
* Socket option: connection time out.
@ -112,12 +105,6 @@ public class CassandraProperties {
*/
private boolean ssl = false;
/**
* Whether to enable JMX reporting. Default to false as Cassandra JMX reporting is not
* compatible with Dropwizard Metrics.
*/
private boolean jmxEnabled;
/**
* Pool configuration.
*/
@ -131,24 +118,27 @@ public class CassandraProperties {
this.keyspaceName = keyspaceName;
}
public String getClusterName() {
return this.clusterName;
public String getSessionName() {
return this.sessionName;
}
public void setClusterName(String clusterName) {
this.clusterName = clusterName;
public void setSessionName(String sessionName) {
this.sessionName = sessionName;
}
public List<String> getContactPoints() {
return this.contactPoints;
@Deprecated
@DeprecatedConfigurationProperty(replacement = "spring.data.cassandra.session-name")
public String getClusterName() {
return getSessionName();
}
public int getPort() {
return this.port;
@Deprecated
public void setClusterName(String clusterName) {
setSessionName(clusterName);
}
public void setPort(int port) {
this.port = port;
public List<String> getContactPoints() {
return this.contactPoints;
}
public String getUsername() {
@ -175,28 +165,39 @@ public class CassandraProperties {
this.compression = compression;
}
public ConsistencyLevel getConsistencyLevel() {
public DefaultConsistencyLevel getConsistencyLevel() {
return this.consistencyLevel;
}
public void setConsistencyLevel(ConsistencyLevel consistency) {
public void setConsistencyLevel(DefaultConsistencyLevel consistency) {
this.consistencyLevel = consistency;
}
public ConsistencyLevel getSerialConsistencyLevel() {
public DefaultConsistencyLevel getSerialConsistencyLevel() {
return this.serialConsistencyLevel;
}
public void setSerialConsistencyLevel(ConsistencyLevel serialConsistency) {
public void setSerialConsistencyLevel(DefaultConsistencyLevel serialConsistency) {
this.serialConsistencyLevel = serialConsistency;
}
public int getPageSize() {
return this.pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
@Deprecated
@DeprecatedConfigurationProperty(replacement = "spring.data.cassandra.page-size")
public int getFetchSize() {
return this.fetchSize;
return getPageSize();
}
@Deprecated
public void setFetchSize(int fetchSize) {
this.fetchSize = fetchSize;
setPageSize(fetchSize);
}
public Duration getConnectTimeout() {
@ -223,14 +224,6 @@ public class CassandraProperties {
this.ssl = ssl;
}
public boolean isJmxEnabled() {
return this.jmxEnabled;
}
public void setJmxEnabled(boolean jmxEnabled) {
this.jmxEnabled = jmxEnabled;
}
public String getSchemaAction() {
return this.schemaAction;
}
@ -255,11 +248,6 @@ public class CassandraProperties {
@DurationUnit(ChronoUnit.SECONDS)
private Duration idleTimeout = Duration.ofSeconds(120);
/**
* Pool timeout when trying to acquire a connection from a host's pool.
*/
private Duration poolTimeout = Duration.ofMillis(5000);
/**
* Heartbeat interval after which a message is sent on an idle connection to make
* sure it's still alive. If a duration suffix is not specified, seconds will be
@ -281,14 +269,6 @@ public class CassandraProperties {
this.idleTimeout = idleTimeout;
}
public Duration getPoolTimeout() {
return this.poolTimeout;
}
public void setPoolTimeout(Duration poolTimeout) {
this.poolTimeout = poolTimeout;
}
public Duration getHeartbeatInterval() {
return this.heartbeatInterval;
}
@ -307,4 +287,26 @@ public class CassandraProperties {
}
/**
* Name of the algorithm used to compress protocol frames.
*/
public enum Compression {
/**
* Requires 'net.jpountz.lz4:lz4'.
*/
LZ4,
/**
* Requires org.xerial.snappy:snappy-java.
*/
SNAPPY,
/**
* No compression.
*/
NONE;
}
}

@ -1,39 +0,0 @@
/*
* Copyright 2012-2019 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
*
* https://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.boot.autoconfigure.cassandra;
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Cluster.Initializer;
/**
* {@code ClusterFactory} provides control over the creation of a {@link Cluster} from an
* {@link Initializer}.
*
* @author Steffen F. Qvistgaard
* @since 2.2.0
*/
@FunctionalInterface
public interface ClusterFactory {
/**
* Creates a {@link Cluster} from the given {@link Initializer}.
* @param initializer the {@code Initializer}
* @return the {@code Cluster}
*/
Cluster create(Initializer initializer);
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2019 the original author or authors.
* Copyright 2012-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -16,24 +16,24 @@
package org.springframework.boot.autoconfigure.cassandra;
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Cluster.Builder;
import com.datastax.oss.driver.api.core.CqlSession;
import com.datastax.oss.driver.api.core.CqlSessionBuilder;
/**
* Callback interface that can be implemented by beans wishing to customize the
* {@link Cluster} via a {@link Builder Cluster.Builder} whilst retaining default
* {@link CqlSession} via a {@link CqlSessionBuilder} whilst retaining default
* auto-configuration.
*
* @author Eddú Meléndez
* @since 1.5.0
* @author Stephane Nicoll
* @since 2.3.0
*/
@FunctionalInterface
public interface ClusterBuilderCustomizer {
public interface CqlSessionBuilderCustomizer {
/**
* Customize the {@link Builder}.
* @param clusterBuilder the builder to customize
* Customize the {@link CqlSessionBuilder}.
* @param cqlSessionBuilder the builder to customize
*/
void customize(Builder clusterBuilder);
void customize(CqlSessionBuilder cqlSessionBuilder);
}

@ -0,0 +1,39 @@
/*
* Copyright 2012-2020 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
*
* https://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.boot.autoconfigure.cassandra;
import com.datastax.oss.driver.api.core.config.DriverConfigLoader;
import com.datastax.oss.driver.api.core.config.ProgrammaticDriverConfigLoaderBuilder;
/**
* Callback interface that can be implemented by beans wishing to customize the
* {@link DriverConfigLoader} via a {@link DriverConfigLoaderBuilderCustomizer} whilst
* retaining default auto-configuration.
*
* @author Stephane Nicoll
* @since 2.3.0
*/
public interface DriverConfigLoaderBuilderCustomizer {
/**
* Customize the {@linkplain ProgrammaticDriverConfigLoaderBuilder DriverConfigLoader
* builder}.
* @param builder the builder to customize
*/
void customizer(ProgrammaticDriverConfigLoaderBuilder builder);
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2019 the original author or authors.
* Copyright 2012-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -19,28 +19,25 @@ package org.springframework.boot.autoconfigure.data.cassandra;
import java.util.Collections;
import java.util.List;
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Session;
import com.datastax.oss.driver.api.core.CqlSession;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.boot.autoconfigure.AutoConfigurationPackages;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration;
import org.springframework.boot.autoconfigure.cassandra.CassandraProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.domain.EntityScanPackages;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.context.properties.PropertyMapper;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.data.cassandra.SessionFactory;
import org.springframework.data.cassandra.config.CassandraEntityClassScanner;
import org.springframework.data.cassandra.config.CassandraSessionFactoryBean;
import org.springframework.data.cassandra.config.SchemaAction;
import org.springframework.data.cassandra.config.SessionFactoryFactoryBean;
import org.springframework.data.cassandra.core.CassandraAdminOperations;
import org.springframework.data.cassandra.core.CassandraOperations;
import org.springframework.data.cassandra.core.CassandraTemplate;
@ -60,19 +57,15 @@ import org.springframework.data.cassandra.core.mapping.SimpleUserTypeResolver;
* @since 1.3.0
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass({ Cluster.class, CassandraAdminOperations.class })
@ConditionalOnBean(Cluster.class)
@EnableConfigurationProperties(CassandraProperties.class)
@ConditionalOnClass({ CqlSession.class, CassandraAdminOperations.class })
@ConditionalOnBean(CqlSession.class)
@AutoConfigureAfter(CassandraAutoConfiguration.class)
public class CassandraDataAutoConfiguration {
private final CassandraProperties properties;
private final CqlSession session;
private final Cluster cluster;
public CassandraDataAutoConfiguration(CassandraProperties properties, Cluster cluster) {
this.properties = properties;
this.cluster = cluster;
public CassandraDataAutoConfiguration(CqlSession session) {
this.session = session;
}
@Bean
@ -87,16 +80,11 @@ public class CassandraDataAutoConfiguration {
if (!packages.isEmpty()) {
context.setInitialEntitySet(CassandraEntityClassScanner.scan(packages));
}
PropertyMapper.get().from(this.properties::getKeyspaceName).whenHasText().as(this::createSimpleUserTypeResolver)
.to(context::setUserTypeResolver);
context.setUserTypeResolver(new SimpleUserTypeResolver(this.session));
context.setCustomConversions(conversions);
return context;
}
private SimpleUserTypeResolver createSimpleUserTypeResolver(String keyspaceName) {
return new SimpleUserTypeResolver(this.cluster, keyspaceName);
}
@Bean
@ConditionalOnMissingBean
public CassandraConverter cassandraConverter(CassandraMappingContext mapping,
@ -107,12 +95,11 @@ public class CassandraDataAutoConfiguration {
}
@Bean
@ConditionalOnMissingBean(Session.class)
public CassandraSessionFactoryBean cassandraSession(Environment environment, CassandraConverter converter) {
CassandraSessionFactoryBean session = new CassandraSessionFactoryBean();
session.setCluster(this.cluster);
@ConditionalOnMissingBean(SessionFactory.class)
public SessionFactoryFactoryBean cassandraSession(Environment environment, CassandraConverter converter) {
SessionFactoryFactoryBean session = new SessionFactoryFactoryBean();
session.setSession(this.session);
session.setConverter(converter);
session.setKeyspaceName(this.properties.getKeyspaceName());
Binder binder = Binder.get(environment);
binder.bind("spring.data.cassandra.schema-action", SchemaAction.class).ifBound(session::setSchemaAction);
return session;
@ -120,8 +107,8 @@ public class CassandraDataAutoConfiguration {
@Bean
@ConditionalOnMissingBean(CassandraOperations.class)
public CassandraTemplate cassandraTemplate(Session session, CassandraConverter converter) {
return new CassandraTemplate(session, converter);
public CassandraTemplate cassandraTemplate(SessionFactory sessionFactory, CassandraConverter converter) {
return new CassandraTemplate(sessionFactory, converter);
}
@Bean

@ -1,5 +1,5 @@
/*
* Copyright 2012-2019 the original author or authors.
* Copyright 2012-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -16,8 +16,7 @@
package org.springframework.boot.autoconfigure.data.cassandra;
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Session;
import com.datastax.oss.driver.api.core.CqlSession;
import reactor.core.publisher.Flux;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
@ -44,14 +43,14 @@ import org.springframework.data.cassandra.core.cql.session.DefaultReactiveSessio
* @since 2.0.0
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass({ Cluster.class, ReactiveCassandraTemplate.class, Flux.class })
@ConditionalOnBean(Session.class)
@ConditionalOnClass({ CqlSession.class, ReactiveCassandraTemplate.class, Flux.class })
@ConditionalOnBean(CqlSession.class)
@AutoConfigureAfter(CassandraDataAutoConfiguration.class)
public class CassandraReactiveDataAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public ReactiveSession reactiveCassandraSession(Session session) {
public ReactiveSession reactiveCassandraSession(CqlSession session) {
return new DefaultBridgedReactiveSession(session);
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2019 the original author or authors.
* Copyright 2012-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -16,7 +16,7 @@
package org.springframework.boot.autoconfigure.data.cassandra;
import com.datastax.driver.core.Session;
import com.datastax.oss.driver.api.core.CqlSession;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
@ -38,7 +38,7 @@ import org.springframework.data.cassandra.repository.support.CassandraRepository
* @since 1.3.0
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass({ Session.class, CassandraRepository.class })
@ConditionalOnClass({ CqlSession.class, CassandraRepository.class })
@ConditionalOnRepositoryType(store = "cassandra", type = RepositoryType.IMPERATIVE)
@ConditionalOnMissingBean(CassandraRepositoryFactoryBean.class)
@Import(CassandraRepositoriesRegistrar.class)

@ -1,5 +1,5 @@
/*
* Copyright 2012-2019 the original author or authors.
* Copyright 2012-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -27,15 +27,11 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.client.reactive.ReactiveElasticsearchClient;
import org.springframework.data.elasticsearch.core.DefaultEntityMapper;
import org.springframework.data.elasticsearch.core.DefaultResultMapper;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.EntityMapper;
import org.springframework.data.elasticsearch.core.ReactiveElasticsearchOperations;
import org.springframework.data.elasticsearch.core.ReactiveElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.ResultsMapper;
import org.springframework.data.elasticsearch.core.convert.ElasticsearchConverter;
import org.springframework.data.elasticsearch.core.convert.MappingElasticsearchConverter;
import org.springframework.data.elasticsearch.core.mapping.SimpleElasticsearchMappingContext;
@ -48,6 +44,7 @@ import org.springframework.web.reactive.function.client.WebClient;
* their order of execution.
*
* @author Brian Clozel
* @author Scott Frederick
*/
abstract class ElasticsearchDataConfiguration {
@ -66,18 +63,6 @@ abstract class ElasticsearchDataConfiguration {
return new SimpleElasticsearchMappingContext();
}
@Bean
@ConditionalOnMissingBean
EntityMapper entityMapper(SimpleElasticsearchMappingContext mappingContext) {
return new DefaultEntityMapper(mappingContext);
}
@Bean
@ConditionalOnMissingBean
ResultsMapper resultsMapper(SimpleElasticsearchMappingContext mappingContext, EntityMapper entityMapper) {
return new DefaultResultMapper(mappingContext, entityMapper);
}
}
@Configuration(proxyBeanMethods = false)
@ -87,9 +72,8 @@ abstract class ElasticsearchDataConfiguration {
@Bean
@ConditionalOnMissingBean(value = ElasticsearchOperations.class, name = "elasticsearchTemplate")
@ConditionalOnBean(RestHighLevelClient.class)
ElasticsearchRestTemplate elasticsearchTemplate(RestHighLevelClient client, ElasticsearchConverter converter,
ResultsMapper resultsMapper) {
return new ElasticsearchRestTemplate(client, converter, resultsMapper);
ElasticsearchRestTemplate elasticsearchTemplate(RestHighLevelClient client, ElasticsearchConverter converter) {
return new ElasticsearchRestTemplate(client, converter);
}
}
@ -101,10 +85,10 @@ abstract class ElasticsearchDataConfiguration {
@Bean
@ConditionalOnMissingBean(value = ElasticsearchOperations.class, name = "elasticsearchTemplate")
@ConditionalOnBean(Client.class)
ElasticsearchTemplate elasticsearchTemplate(Client client, ElasticsearchConverter converter,
ResultsMapper resultsMapper) {
@Deprecated
ElasticsearchTemplate elasticsearchTemplate(Client client, ElasticsearchConverter converter) {
try {
return new ElasticsearchTemplate(client, converter, resultsMapper);
return new ElasticsearchTemplate(client, converter);
}
catch (Exception ex) {
throw new IllegalStateException(ex);
@ -121,9 +105,8 @@ abstract class ElasticsearchDataConfiguration {
@ConditionalOnMissingBean(value = ReactiveElasticsearchOperations.class, name = "reactiveElasticsearchTemplate")
@ConditionalOnBean(ReactiveElasticsearchClient.class)
ReactiveElasticsearchTemplate reactiveElasticsearchTemplate(ReactiveElasticsearchClient client,
ElasticsearchConverter converter, ResultsMapper resultsMapper) {
ReactiveElasticsearchTemplate template = new ReactiveElasticsearchTemplate(client, converter,
resultsMapper);
ElasticsearchConverter converter) {
ReactiveElasticsearchTemplate template = new ReactiveElasticsearchTemplate(client, converter);
template.setIndicesOptions(IndicesOptions.strictExpandOpenAndForbidClosed());
template.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE);
return template;

@ -1557,6 +1557,33 @@
"level": "error"
}
},
{
"name": "spring.data.cassandra.jmx-enabled",
"type": "java.lang.Boolean",
"description": "Whether to enable JMX reporting. Default to false as Cassandra JMX reporting is not compatible with Dropwizard Metrics.",
"deprecation": {
"reason": "Cassandra no longer providers JMX metrics.",
"level": "error"
}
},
{
"name": "spring.data.cassandra.pool.pool-timeout",
"type": "java.time.Duration",
"description": "Pool timeout when trying to acquire a connection from a host's pool.",
"deprecation": {
"reason": "No longer available.",
"level": "error"
}
},
{
"name": "spring.data.cassandra.port",
"type": "java.lang.Integer",
"description": "Port of the Cassandra server.",
"deprecation": {
"reason": "each contact point must be of the form 'host:port'.",
"level": "error"
}
},
{
"name": "spring.data.cassandra.read-timeout-millis",
"type": "java.lang.Integer",

@ -1,5 +1,5 @@
/*
* Copyright 2012-2019 the original author or authors.
* Copyright 2012-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -16,9 +16,12 @@
package org.springframework.boot.autoconfigure.cassandra;
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Cluster.Initializer;
import com.datastax.driver.core.PoolingOptions;
import com.datastax.oss.driver.api.core.config.DefaultDriverOption;
import com.datastax.oss.driver.api.core.config.DriverConfigLoader;
import com.datastax.oss.driver.api.core.config.DriverExecutionProfile;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigParseOptions;
import com.typesafe.config.impl.Parseable;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
@ -27,7 +30,6 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
/**
* Tests for {@link CassandraAutoConfiguration}
@ -41,110 +43,66 @@ class CassandraAutoConfigurationTests {
.withConfiguration(AutoConfigurations.of(CassandraAutoConfiguration.class));
@Test
void createClusterWithDefault() {
void driverConfigLoaderWithDefaultConfiguration() {
this.contextRunner.run((context) -> {
assertThat(context).hasSingleBean(Cluster.class);
assertThat(context.getBean(Cluster.class).getClusterName()).startsWith("cluster");
assertThat(context).hasSingleBean(DriverConfigLoader.class);
assertThat(context.getBean(DriverConfigLoader.class).getInitialConfig().getDefaultProfile()
.isDefined(DefaultDriverOption.SESSION_NAME)).isFalse();
});
}
@Test
void createClusterWithOverrides() {
this.contextRunner.withPropertyValues("spring.data.cassandra.cluster-name=testcluster").run((context) -> {
assertThat(context).hasSingleBean(Cluster.class);
assertThat(context.getBean(Cluster.class).getClusterName()).isEqualTo("testcluster");
void driverConfigLoaderWithCustomSessionName() {
this.contextRunner.withPropertyValues("spring.data.cassandra.session-name=testcluster").run((context) -> {
assertThat(context).hasSingleBean(DriverConfigLoader.class);
assertThat(context.getBean(DriverConfigLoader.class).getInitialConfig().getDefaultProfile()
.getString(DefaultDriverOption.SESSION_NAME)).isEqualTo("testcluster");
});
}
@Test
void createCustomizeCluster() {
this.contextRunner.withUserConfiguration(MockCustomizerConfig.class).run((context) -> {
assertThat(context).hasSingleBean(Cluster.class);
assertThat(context).hasSingleBean(ClusterBuilderCustomizer.class);
});
}
@Test
void customizerOverridesAutoConfig() {
this.contextRunner.withUserConfiguration(SimpleCustomizerConfig.class)
.withPropertyValues("spring.data.cassandra.cluster-name=testcluster").run((context) -> {
assertThat(context).hasSingleBean(Cluster.class);
assertThat(context.getBean(Cluster.class).getClusterName()).isEqualTo("overridden-name");
void driverConfigLoaderWithCustomSessionNameAndCustomizer() {
this.contextRunner.withUserConfiguration(SimpleDriverConfigLoaderBuilderCustomizerConfig.class)
.withPropertyValues("spring.data.cassandra.session-name=testcluster").run((context) -> {
assertThat(context).hasSingleBean(DriverConfigLoader.class);
assertThat(context.getBean(DriverConfigLoader.class).getInitialConfig().getDefaultProfile()
.getString(DefaultDriverOption.SESSION_NAME)).isEqualTo("overridden-name");
});
}
@Test
void defaultPoolOptions() {
void driverConfigLoaderApplyConsistentDefaults() {
this.contextRunner.run((context) -> {
assertThat(context).hasSingleBean(Cluster.class);
PoolingOptions poolingOptions = context.getBean(Cluster.class).getConfiguration().getPoolingOptions();
assertThat(poolingOptions.getIdleTimeoutSeconds()).isEqualTo(PoolingOptions.DEFAULT_IDLE_TIMEOUT_SECONDS);
assertThat(poolingOptions.getPoolTimeoutMillis()).isEqualTo(PoolingOptions.DEFAULT_POOL_TIMEOUT_MILLIS);
assertThat(poolingOptions.getHeartbeatIntervalSeconds())
.isEqualTo(PoolingOptions.DEFAULT_HEARTBEAT_INTERVAL_SECONDS);
assertThat(poolingOptions.getMaxQueueSize()).isEqualTo(PoolingOptions.DEFAULT_MAX_QUEUE_SIZE);
Config defaultConfig = defaultConfig();
DriverExecutionProfile config = context.getBean(DriverConfigLoader.class).getInitialConfig()
.getDefaultProfile();
// TODO
});
}
@Test
void customizePoolOptions() {
void driverConfigLoaderCustomizePoolOptions() {
this.contextRunner.withPropertyValues("spring.data.cassandra.pool.idle-timeout=42",
"spring.data.cassandra.pool.pool-timeout=52", "spring.data.cassandra.pool.heartbeat-interval=62",
"spring.data.cassandra.pool.max-queue-size=72").run((context) -> {
assertThat(context).hasSingleBean(Cluster.class);
PoolingOptions poolingOptions = context.getBean(Cluster.class).getConfiguration()
.getPoolingOptions();
assertThat(poolingOptions.getIdleTimeoutSeconds()).isEqualTo(42);
assertThat(poolingOptions.getPoolTimeoutMillis()).isEqualTo(52);
assertThat(poolingOptions.getHeartbeatIntervalSeconds()).isEqualTo(62);
assertThat(poolingOptions.getMaxQueueSize()).isEqualTo(72);
"spring.data.cassandra.pool.heartbeat-interval=62", "spring.data.cassandra.pool.max-queue-size=72")
.run((context) -> {
DriverExecutionProfile config = context.getBean(DriverConfigLoader.class).getInitialConfig()
.getDefaultProfile();
assertThat(config.getInt(DefaultDriverOption.HEARTBEAT_TIMEOUT)).isEqualTo(42);
assertThat(config.getInt(DefaultDriverOption.HEARTBEAT_INTERVAL)).isEqualTo(62);
assertThat(config.getInt(DefaultDriverOption.REQUEST_THROTTLER_MAX_QUEUE_SIZE)).isEqualTo(72);
});
}
@Test
void clusterFactoryIsCalledToCreateCluster() {
this.contextRunner.withUserConfiguration(ClusterFactoryConfig.class)
.run((context) -> assertThat(context.getBean(TestClusterFactory.class).initializer).isNotNull());
private static Config defaultConfig() {
return Parseable.newResources("reference.conf", ConfigParseOptions.defaults()).parse().toConfig();
}
@Configuration(proxyBeanMethods = false)
static class MockCustomizerConfig {
static class SimpleDriverConfigLoaderBuilderCustomizerConfig {
@Bean
ClusterBuilderCustomizer customizer() {
return mock(ClusterBuilderCustomizer.class);
}
}
@Configuration(proxyBeanMethods = false)
static class SimpleCustomizerConfig {
@Bean
ClusterBuilderCustomizer customizer() {
return (clusterBuilder) -> clusterBuilder.withClusterName("overridden-name");
}
}
@Configuration(proxyBeanMethods = false)
static class ClusterFactoryConfig {
@Bean
TestClusterFactory clusterFactory() {
return new TestClusterFactory();
}
}
static class TestClusterFactory implements ClusterFactory {
private Initializer initializer = null;
@Override
public Cluster create(Initializer initializer) {
this.initializer = initializer;
return Cluster.buildFrom(initializer);
DriverConfigLoaderBuilderCustomizer customizer() {
return (builder) -> builder.withString(DefaultDriverOption.SESSION_NAME, "overridden-name");
}
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2019 the original author or authors.
* Copyright 2012-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -16,10 +16,10 @@
package org.springframework.boot.autoconfigure.data.cassandra;
import java.net.InetSocketAddress;
import java.time.Duration;
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Session;
import com.datastax.oss.driver.api.core.CqlSession;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@ -29,11 +29,14 @@ import org.testcontainers.junit.jupiter.Testcontainers;
import org.springframework.boot.autoconfigure.AutoConfigurationPackages;
import org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration;
import org.springframework.boot.autoconfigure.cassandra.CqlSessionBuilderCustomizer;
import org.springframework.boot.autoconfigure.data.cassandra.city.City;
import org.springframework.boot.test.util.TestPropertyValues;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.data.cassandra.config.CassandraSessionFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.cassandra.config.SchemaAction;
import org.springframework.data.cassandra.config.SessionFactoryFactoryBean;
import static org.assertj.core.api.Assertions.assertThat;
@ -55,8 +58,9 @@ class CassandraDataAutoConfigurationIntegrationTests {
@BeforeEach
void setUp() {
this.context = new AnnotationConfigApplicationContext();
this.context.register(TestConfiguration.class);
TestPropertyValues
.of("spring.data.cassandra.port=" + cassandra.getFirstMappedPort(),
.of("spring.data.cassandra.contact-points:localhost:" + cassandra.getFirstMappedPort(),
"spring.data.cassandra.read-timeout=24000", "spring.data.cassandra.connect-timeout=10000")
.applyTo(this.context.getEnvironment());
}
@ -74,8 +78,8 @@ class CassandraDataAutoConfigurationIntegrationTests {
AutoConfigurationPackages.register(this.context, cityPackage);
this.context.register(CassandraAutoConfiguration.class, CassandraDataAutoConfiguration.class);
this.context.refresh();
CassandraSessionFactoryBean bean = this.context.getBean(CassandraSessionFactoryBean.class);
assertThat(bean.getSchemaAction()).isEqualTo(SchemaAction.NONE);
assertThat(this.context.getBean(SessionFactoryFactoryBean.class)).hasFieldOrPropertyWithValue("schemaAction",
SchemaAction.NONE);
}
@Test
@ -87,17 +91,28 @@ class CassandraDataAutoConfigurationIntegrationTests {
"spring.data.cassandra.keyspaceName=boot_test").applyTo(this.context);
this.context.register(CassandraAutoConfiguration.class, CassandraDataAutoConfiguration.class);
this.context.refresh();
CassandraSessionFactoryBean bean = this.context.getBean(CassandraSessionFactoryBean.class);
assertThat(bean.getSchemaAction()).isEqualTo(SchemaAction.RECREATE_DROP_UNUSED);
assertThat(this.context.getBean(SessionFactoryFactoryBean.class)).hasFieldOrPropertyWithValue("schemaAction",
SchemaAction.RECREATE_DROP_UNUSED);
}
private void createTestKeyspaceIfNotExists() {
Cluster cluster = Cluster.builder().withoutJMXReporting().withPort(cassandra.getFirstMappedPort())
.addContactPoint(cassandra.getContainerIpAddress()).build();
try (Session session = cluster.connect()) {
try (CqlSession session = CqlSession.builder()
.addContactPoint(
new InetSocketAddress(cassandra.getContainerIpAddress(), cassandra.getFirstMappedPort()))
.withLocalDatacenter("datacenter1").build()) {
session.execute("CREATE KEYSPACE IF NOT EXISTS boot_test"
+ " WITH REPLICATION = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };");
}
}
@Configuration
static class TestConfiguration {
@Bean
CqlSessionBuilderCustomizer sessionCustomizer() {
return (builder) -> builder.withLocalDatacenter("datacenter1");
}
}
}

@ -19,7 +19,7 @@ package org.springframework.boot.autoconfigure.data.cassandra;
import java.util.Collections;
import java.util.Set;
import com.datastax.driver.core.Session;
import com.datastax.oss.driver.api.core.CqlSession;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
@ -101,7 +101,7 @@ class CassandraDataAutoConfigurationTests {
@Test
void clusterDoesNotExist() {
this.context = new AnnotationConfigApplicationContext(CassandraDataAutoConfiguration.class);
assertThat(this.context.getBeansOfType(Session.class)).isEmpty();
assertThat(this.context.getBeansOfType(CqlSession.class)).isEmpty();
}
void load(Class<?>... config) {
@ -119,8 +119,8 @@ class CassandraDataAutoConfigurationTests {
static class TestConfiguration {
@Bean
Session getObject() {
return mock(Session.class);
CqlSession cqlSession() {
return mock(CqlSession.class);
}
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2019 the original author or authors.
* Copyright 2012-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -18,7 +18,7 @@ package org.springframework.boot.autoconfigure.data.cassandra;
import java.util.Set;
import com.datastax.driver.core.Session;
import com.datastax.oss.driver.api.core.CqlSession;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
@ -99,8 +99,8 @@ class CassandraReactiveDataAutoConfigurationTests {
static class TestConfiguration {
@Bean
Session session() {
return mock(Session.class);
CqlSession cqlSession() {
return mock(CqlSession.class);
}
}

@ -18,8 +18,8 @@ package org.springframework.boot.autoconfigure.data.cassandra;
import java.util.Set;
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Session;
import com.datastax.oss.driver.api.core.CqlSession;
import com.datastax.oss.driver.api.core.CqlSessionBuilder;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
@ -61,7 +61,7 @@ class CassandraReactiveRepositoriesAutoConfigurationTests {
void testDefaultRepositoryConfiguration() {
this.contextRunner.withUserConfiguration(DefaultConfiguration.class).run((context) -> {
assertThat(context).hasSingleBean(ReactiveCityRepository.class);
assertThat(context).hasSingleBean(Cluster.class);
assertThat(context).hasSingleBean(CqlSessionBuilder.class);
assertThat(getInitialEntitySet(context)).hasSize(1);
});
}
@ -69,7 +69,7 @@ class CassandraReactiveRepositoriesAutoConfigurationTests {
@Test
void testNoRepositoryConfiguration() {
this.contextRunner.withUserConfiguration(EmptyConfiguration.class).run((context) -> {
assertThat(context).hasSingleBean(Cluster.class);
assertThat(context).hasSingleBean(CqlSessionBuilder.class);
assertThat(getInitialEntitySet(context)).isEmpty();
});
}
@ -106,8 +106,8 @@ class CassandraReactiveRepositoriesAutoConfigurationTests {
static class TestConfiguration {
@Bean
Session session() {
return mock(Session.class);
CqlSession cqlSession() {
return mock(CqlSession.class);
}
}

@ -18,8 +18,8 @@ package org.springframework.boot.autoconfigure.data.cassandra;
import java.util.Set;
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Session;
import com.datastax.oss.driver.api.core.CqlSession;
import com.datastax.oss.driver.api.core.CqlSessionBuilder;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
@ -59,7 +59,7 @@ class CassandraRepositoriesAutoConfigurationTests {
void testDefaultRepositoryConfiguration() {
this.contextRunner.withUserConfiguration(DefaultConfiguration.class).run((context) -> {
assertThat(context).hasSingleBean(CityRepository.class);
assertThat(context).hasSingleBean(Cluster.class);
assertThat(context).hasSingleBean(CqlSessionBuilder.class);
assertThat(getInitialEntitySet(context)).hasSize(1);
});
}
@ -67,7 +67,7 @@ class CassandraRepositoriesAutoConfigurationTests {
@Test
void testNoRepositoryConfiguration() {
this.contextRunner.withUserConfiguration(EmptyConfiguration.class).run((context) -> {
assertThat(context).hasSingleBean(Cluster.class);
assertThat(context).hasSingleBean(CqlSessionBuilder.class);
assertThat(getInitialEntitySet(context)).isEmpty();
});
}
@ -104,8 +104,8 @@ class CassandraRepositoriesAutoConfigurationTests {
static class TestConfiguration {
@Bean
Session session() {
return mock(Session.class);
CqlSession cqlSession() {
return mock(CqlSession.class);
}
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2019 the original author or authors.
* Copyright 2012-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -16,9 +16,8 @@
package org.springframework.boot.autoconfigure.data.cassandra.city;
import com.datastax.driver.core.DataType.Name;
import org.springframework.data.cassandra.core.mapping.CassandraType;
import org.springframework.data.cassandra.core.mapping.CassandraType.Name;
import org.springframework.data.cassandra.core.mapping.Column;
import org.springframework.data.cassandra.core.mapping.PrimaryKey;
import org.springframework.data.cassandra.core.mapping.Table;

@ -1,5 +1,5 @@
/*
* Copyright 2012-2019 the original author or authors.
* Copyright 2012-2020 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.
@ -47,8 +47,8 @@ import static org.mockito.Mockito.mock;
class ElasticsearchAutoConfigurationTests {
@Container
public static ElasticsearchContainer elasticsearch = new ElasticsearchContainer().withStartupAttempts(5)
.withStartupTimeout(Duration.ofMinutes(10));
public static ElasticsearchContainer elasticsearch = new VersionOverridingElasticsearchContainer()
.withStartupAttempts(5).withStartupTimeout(Duration.ofMinutes(10));
private AnnotationConfigApplicationContext context;
@ -76,6 +76,7 @@ class ElasticsearchAutoConfigurationTests {
}
@Test
@SuppressWarnings("deprecation")
void createTransportClient() {
this.context = new AnnotationConfigApplicationContext();
TestPropertyValues

@ -1,5 +1,5 @@
/*
* Copyright 2012-2019 the original author or authors.
* Copyright 2012-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -30,10 +30,8 @@ import org.springframework.boot.autoconfigure.elasticsearch.rest.RestClientAutoC
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.core.ElasticsearchEntityMapper;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.EntityMapper;
import org.springframework.data.elasticsearch.core.ReactiveElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.convert.ElasticsearchConverter;
import org.springframework.data.elasticsearch.core.mapping.SimpleElasticsearchMappingContext;
@ -48,12 +46,13 @@ import static org.mockito.Mockito.mock;
* @author Artur Konczak
* @author Brian Clozel
* @author Peter-Josef Meisch
* @author Scott Frederick
*/
@Testcontainers(disabledWithoutDocker = true)
class ElasticsearchDataAutoConfigurationTests {
@Container
static ElasticsearchContainer elasticsearch = new ElasticsearchContainer().withStartupAttempts(5)
static ElasticsearchContainer elasticsearch = new VersionOverridingElasticsearchContainer().withStartupAttempts(5)
.withStartupTimeout(Duration.ofMinutes(10));
private ApplicationContextRunner contextRunner = new ApplicationContextRunner().withConfiguration(
@ -71,6 +70,7 @@ class ElasticsearchDataAutoConfigurationTests {
}
@Test
@SuppressWarnings("deprecation")
void defaultTransportBeansAreRegistered() {
this.contextRunner
.withPropertyValues(
@ -83,6 +83,7 @@ class ElasticsearchDataAutoConfigurationTests {
}
@Test
@SuppressWarnings("deprecation")
void defaultTransportBeansNotRegisteredIfNoTransportClient() {
this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(ElasticsearchTemplate.class));
}
@ -91,16 +92,11 @@ class ElasticsearchDataAutoConfigurationTests {
void defaultRestBeansRegistered() {
this.contextRunner.run((context) -> assertThat(context).hasSingleBean(ElasticsearchRestTemplate.class)
.hasSingleBean(ReactiveElasticsearchTemplate.class).hasSingleBean(ElasticsearchConverter.class)
.hasSingleBean(SimpleElasticsearchMappingContext.class).hasSingleBean(EntityMapper.class)
.hasSingleBean(ElasticsearchConverter.class));
}
@Test
void defaultEntityMapperRegistered() {
this.contextRunner.run((context) -> assertThat(context).hasSingleBean(EntityMapper.class));
}
@Test
@SuppressWarnings("deprecation")
void customTransportTemplateShouldBeUsed() {
this.contextRunner.withUserConfiguration(CustomTransportTemplate.class).run((context) -> assertThat(context)
.getBeanNames(ElasticsearchTemplate.class).hasSize(1).contains("elasticsearchTemplate"));
@ -119,16 +115,11 @@ class ElasticsearchDataAutoConfigurationTests {
.contains("reactiveElasticsearchTemplate"));
}
@Test
void customEntityMapperShouldeBeUsed() {
this.contextRunner.withUserConfiguration(CustomEntityMapper.class).run((context) -> assertThat(context)
.getBeanNames(EntityMapper.class).containsExactly("elasticsearchEntityMapper"));
}
@Configuration(proxyBeanMethods = false)
static class CustomTransportTemplate {
@Bean
@SuppressWarnings("deprecation")
ElasticsearchTemplate elasticsearchTemplate() {
return mock(ElasticsearchTemplate.class);
}
@ -155,14 +146,4 @@ class ElasticsearchDataAutoConfigurationTests {
}
@Configuration(proxyBeanMethods = false)
static class CustomEntityMapper {
@Bean
EntityMapper elasticsearchEntityMapper() {
return mock(ElasticsearchEntityMapper.class);
}
}
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2019 the original author or authors.
* Copyright 2012-2020 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.
@ -48,8 +48,8 @@ import static org.assertj.core.api.Assertions.assertThat;
class ElasticsearchRepositoriesAutoConfigurationTests {
@Container
static final ElasticsearchContainer elasticsearch = new ElasticsearchContainer().withStartupAttempts(5)
.withStartupTimeout(Duration.ofMinutes(10));
static final ElasticsearchContainer elasticsearch = new VersionOverridingElasticsearchContainer()
.withStartupAttempts(5).withStartupTimeout(Duration.ofMinutes(10));
private ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(

@ -1,5 +1,5 @@
/*
* Copyright 2012-2019 the original author or authors.
* Copyright 2012-2020 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.
@ -47,7 +47,7 @@ import static org.assertj.core.api.Assertions.assertThat;
public class ReactiveElasticsearchRepositoriesAutoConfigurationTests {
@Container
static ElasticsearchContainer elasticsearch = new ElasticsearchContainer().withStartupAttempts(5)
static ElasticsearchContainer elasticsearch = new VersionOverridingElasticsearchContainer().withStartupAttempts(5)
.withStartupTimeout(Duration.ofMinutes(10));
private ApplicationContextRunner contextRunner = new ApplicationContextRunner()

@ -1,5 +1,5 @@
/*
* Copyright 2012-2019 the original author or authors.
* Copyright 2012-2020 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.
@ -47,7 +47,7 @@ import static org.mockito.Mockito.mock;
public class ReactiveRestClientAutoConfigurationTests {
@Container
static ElasticsearchContainer elasticsearch = new ElasticsearchContainer().withStartupAttempts(5)
static ElasticsearchContainer elasticsearch = new VersionOverridingElasticsearchContainer().withStartupAttempts(5)
.withStartupTimeout(Duration.ofMinutes(10));
private ApplicationContextRunner contextRunner = new ApplicationContextRunner()
@ -83,9 +83,10 @@ public class ReactiveRestClientAutoConfigurationTests {
Map<String, String> source = new HashMap<>();
source.put("a", "alpha");
source.put("b", "bravo");
IndexRequest index = new IndexRequest("foo", "bar", "1").source(source);
GetRequest getRequest = new GetRequest("foo", "bar", "1");
GetResult getResult = client.index(index).then(client.get(getRequest)).block();
IndexRequest indexRequest = new IndexRequest("foo").id("1").source(source);
GetRequest getRequest = new GetRequest("foo").id("1");
GetResult getResult = client.index(indexRequest).then(client.get(getRequest)).block();
assertThat(getResult).isNotNull();
assertThat(getResult.isExists()).isTrue();
});
}

@ -0,0 +1,41 @@
/*
* Copyright 2012-2020 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
*
* https://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.boot.autoconfigure.data.elasticsearch;
import org.testcontainers.elasticsearch.ElasticsearchContainer;
/**
* Extension of {@link ElasticsearchContainer} to override default version.
*
* @author Scott Frederick
*/
public class VersionOverridingElasticsearchContainer extends ElasticsearchContainer {
/**
* Elasticsearch Docker base URL
*/
private static final String ELASTICSEARCH_IMAGE = "docker.elastic.co/elasticsearch/elasticsearch";
/**
* Elasticsearch version
*/
protected static final String ELASTICSEARCH_VERSION = "7.5.1";
public VersionOverridingElasticsearchContainer() {
super(ELASTICSEARCH_IMAGE + ":" + ELASTICSEARCH_VERSION);
}
}

@ -159,11 +159,11 @@ bom {
]
}
}
library('Cassandra Driver', '3.7.2') {
group('com.datastax.cassandra') {
library('Cassandra Driver', '4.3.1') {
group('com.datastax.oss') {
modules = [
'cassandra-driver-core',
'cassandra-driver-mapping'
'java-driver-core',
'java-driver-query-builder'
]
}
}
@ -288,7 +288,7 @@ bom {
]
}
}
library('Elasticsearch', '6.8.5') {
library('Elasticsearch', '7.5.1') {
group('org.elasticsearch') {
modules = [
'elasticsearch'
@ -1663,7 +1663,7 @@ bom {
]
}
}
library('Spring Data Releasetrain', 'Moore-SR3') {
library('Spring Data Releasetrain', 'Neumann-BUILD-SNAPSHOT') {
group('org.springframework.data') {
imports = [
'spring-data-releasetrain'

@ -6,7 +6,7 @@ plugins {
description = 'Spring Boot Testing Support'
dependencies {
compileOnly "com.datastax.cassandra:cassandra-driver-core"
compileOnly "com.datastax.oss:java-driver-core"
compileOnly "javax.servlet:javax.servlet-api"
compileOnly "junit:junit"
compileOnly "org.junit.jupiter:junit-jupiter"

@ -1,48 +0,0 @@
/*
* Copyright 2012-2019 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
*
* https://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 smoketest.data.cassandra;
import java.util.UUID;
import org.springframework.data.cassandra.core.mapping.PrimaryKey;
import org.springframework.data.cassandra.core.mapping.Table;
@Table
public class Customer {
@PrimaryKey
private UUID id;
private String firstName;
private String lastName;
public Customer() {
}
public Customer(UUID id, String firstName, String lastName) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
@Override
public String toString() {
return String.format("Customer[id=%s, firstName='%s', lastName='%s']", this.id, this.firstName, this.lastName);
}
}

@ -1,32 +0,0 @@
/*
* Copyright 2012-2019 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
*
* https://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 smoketest.data.cassandra;
import java.util.List;
import org.springframework.data.cassandra.repository.Query;
import org.springframework.data.repository.CrudRepository;
public interface CustomerRepository extends CrudRepository<Customer, String> {
@Query("Select * from customer where firstname=?0")
Customer findByFirstName(String firstName);
@Query("Select * from customer where lastname=?0")
List<Customer> findByLastName(String lastName);
}

@ -1,64 +0,0 @@
/*
* Copyright 2012-2019 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
*
* https://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 smoketest.data.cassandra;
import com.datastax.driver.core.utils.UUIDs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SampleCassandraApplication implements CommandLineRunner {
@Autowired
private CustomerRepository repository;
@Override
public void run(String... args) throws Exception {
this.repository.deleteAll();
// save a couple of customers
this.repository.save(new Customer(UUIDs.timeBased(), "Alice", "Smith"));
this.repository.save(new Customer(UUIDs.timeBased(), "Bob", "Smith"));
// fetch all customers
System.out.println("Customers found with findAll():");
System.out.println("-------------------------------");
for (Customer customer : this.repository.findAll()) {
System.out.println(customer);
}
System.out.println();
// fetch an individual customer
System.out.println("Customer found with findByFirstName('Alice'):");
System.out.println("--------------------------------");
System.out.println(this.repository.findByFirstName("Alice"));
System.out.println("Customers found with findByLastName('Smith'):");
System.out.println("--------------------------------");
for (Customer customer : this.repository.findByLastName("Smith")) {
System.out.println(customer);
}
}
public static void main(String[] args) {
SpringApplication.run(SampleCassandraApplication.class, args);
}
}

@ -1,44 +0,0 @@
/*
* Copyright 2012-2019 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
*
* https://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 smoketest.data.cassandra;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.cassandraunit.spring.CassandraUnitDependencyInjectionTestExecutionListener;
import org.springframework.core.Ordered;
public class OrderedCassandraTestExecutionListener extends CassandraUnitDependencyInjectionTestExecutionListener {
private static final Log logger = LogFactory.getLog(OrderedCassandraTestExecutionListener.class);
@Override
public int getOrder() {
return Ordered.HIGHEST_PRECEDENCE;
}
@Override
protected void cleanServer() {
try {
super.cleanServer();
}
catch (Exception ex) {
logger.warn("Failure during server cleanup", ex);
}
}
}

@ -1,56 +0,0 @@
/*
* Copyright 2012-2019 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
*
* https://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 smoketest.data.cassandra;
import java.io.File;
import org.cassandraunit.spring.CassandraDataSet;
import org.cassandraunit.spring.EmbeddedCassandra;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.TestExecutionListeners.MergeMode;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link SampleCassandraApplication}.
*/
@TestExecutionListeners(mergeMode = MergeMode.MERGE_WITH_DEFAULTS,
listeners = { OrderedCassandraTestExecutionListener.class })
@ExtendWith(OutputCaptureExtension.class)
@SpringBootTest
@CassandraDataSet(keyspace = "mykeyspace", value = "setup.cql")
@EmbeddedCassandra(timeout = 60000)
class SampleCassandraApplicationTests {
@Test
void testDefaultSettings(CapturedOutput output) {
Assumptions.assumeFalse(this::runningOnWindows);
assertThat(output).contains("firstName='Alice', lastName='Smith'");
}
private boolean runningOnWindows() {
return File.separatorChar == '\\';
}
}

@ -1,3 +0,0 @@
CREATE TABLE customer (id TimeUUID PRIMARY KEY, firstname text, lastname text);
CREATE INDEX customerfistnameindex ON customer (firstname);
CREATE INDEX customersecondnameindex ON customer (lastname);
Loading…
Cancel
Save