use of com.datastax.oss.driver.api.core.CqlSessionBuilder in project spring-boot by spring-projects.
the class CassandraAutoConfiguration method cassandraSessionBuilder.
@Bean
@ConditionalOnMissingBean
@Scope("prototype")
public CqlSessionBuilder cassandraSessionBuilder(CassandraProperties properties, DriverConfigLoader driverConfigLoader, ObjectProvider<CqlSessionBuilderCustomizer> builderCustomizers) {
CqlSessionBuilder builder = CqlSession.builder().withConfigLoader(driverConfigLoader);
configureAuthentication(properties, builder);
configureSsl(properties, builder);
builder.withKeyspace(properties.getKeyspaceName());
builderCustomizers.orderedStream().forEach((customizer) -> customizer.customize(builder));
return builder;
}
use of com.datastax.oss.driver.api.core.CqlSessionBuilder in project zeppelin by apache.
the class CassandraInterpreter method open.
@Override
public void open() {
final String[] addresses = getProperty(CASSANDRA_HOSTS, DEFAULT_HOST).trim().split(",");
final int port = parseInt(getProperty(CASSANDRA_PORT, DEFAULT_PORT));
Collection<InetSocketAddress> hosts = new ArrayList<>();
for (String address : addresses) {
if (!StringUtils.isBlank(address)) {
LOGGER.debug("Adding contact point: {}", address);
if (InetAddresses.isInetAddress(address)) {
hosts.add(new InetSocketAddress(address, port));
} else {
hosts.add(InetSocketAddress.createUnresolved(address, port));
}
}
}
LOGGER.info("Bootstrapping Cassandra Java Driver to connect to {} on port {}", getProperty(CASSANDRA_HOSTS), port);
DriverConfigLoader loader = createLoader();
LOGGER.debug("Creating cluster builder");
CqlSessionBuilder clusterBuilder = CqlSession.builder().withApplicationName("Zeppelin").withApplicationVersion("");
if (!hosts.isEmpty()) {
LOGGER.debug("Adding contact points");
clusterBuilder.addContactPoints(hosts);
}
String username = getProperty(CASSANDRA_CREDENTIALS_USERNAME, NONE_VALUE).trim();
String password = getProperty(CASSANDRA_CREDENTIALS_PASSWORD, NONE_VALUE).trim();
if (StringUtils.isNotBlank(username) && StringUtils.isNotBlank(password) && !NONE_VALUE.equalsIgnoreCase(username) && !NONE_VALUE.equalsIgnoreCase(password)) {
LOGGER.debug("Adding credentials. Username = {}", username);
clusterBuilder.withAuthCredentials(username, password);
}
String keyspace = getProperty(CASSANDRA_KEYSPACE_NAME, DEFAULT_KEYSPACE);
if (StringUtils.isNotBlank(keyspace) && !DEFAULT_KEYSPACE.equalsIgnoreCase(keyspace)) {
LOGGER.debug("Set default keyspace");
clusterBuilder.withKeyspace(keyspace);
}
final String runWithSSL = getProperty(CASSANDRA_WITH_SSL, "false");
if ("true".equalsIgnoreCase(runWithSSL)) {
LOGGER.debug("Using SSL");
try {
final SSLContext sslContext;
{
final KeyStore trustStore = KeyStore.getInstance("JKS");
final InputStream stream = Files.newInputStream(Paths.get(getProperty(CASSANDRA_TRUSTSTORE_PATH)));
trustStore.load(stream, getProperty(CASSANDRA_TRUSTSTORE_PASSWORD).toCharArray());
final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(trustStore);
sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
}
clusterBuilder = clusterBuilder.withSslContext(sslContext);
} catch (Exception e) {
LOGGER.error("Exception initializing SSL {}", e.toString());
}
} else {
LOGGER.debug("Not using SSL");
}
LOGGER.debug("Creating CqlSession");
session = clusterBuilder.withConfigLoader(loader).build();
LOGGER.debug("Session configuration");
for (Map.Entry<String, Object> entry : session.getContext().getConfig().getDefaultProfile().entrySet()) {
LOGGER.debug("{} = {}", entry.getKey(), entry.getValue().toString());
}
LOGGER.debug("Creating helper");
helper = new InterpreterLogic(session, properties);
}
use of com.datastax.oss.driver.api.core.CqlSessionBuilder in project janusgraph by JanusGraph.
the class CQLSessionBuilder method build.
/**
* @param configuration configuration to use
* @param baseHostnames will be used only if base configuration is enabled
* @param baseDefaultPort will be used only if base configuration is enabled
* @param baseConfigurationLoaderBuilder will be used only if base configuration is enabled
* @return Returns constructed CqlSession
*/
public CqlSession build(Configuration configuration, String[] baseHostnames, int baseDefaultPort, Duration baseConnectionTimeoutMS, CQLProgrammaticConfigurationLoaderBuilder baseConfigurationLoaderBuilder) throws PermanentBackendException {
final List<String> contactPoints = new ArrayList<>(baseHostnames.length);
for (String contactPoint : baseHostnames) {
if (!contactPoint.contains(":")) {
contactPoint += ":" + baseDefaultPort;
}
contactPoints.add(contactPoint);
}
final CqlSessionBuilder builder = CqlSession.builder();
Stack<DriverConfigLoader> driverConfigLoadersToUse = new Stack<>();
if (configuration.get(CQLConfigOptions.BASE_PROGRAMMATIC_CONFIGURATION_ENABLED)) {
driverConfigLoadersToUse.push(baseConfigurationLoaderBuilder.build(configuration, contactPoints, baseConnectionTimeoutMS));
}
if (configuration.has(CQLConfigOptions.URL_CONFIGURATION)) {
String stringUrlRepresentation = configuration.get(CQLConfigOptions.URL_CONFIGURATION);
URL url;
try {
url = new URL(stringUrlRepresentation);
} catch (MalformedURLException e) {
throw new PermanentBackendException("Malformed URL: " + stringUrlRepresentation, e);
}
driverConfigLoadersToUse.push(DriverConfigLoader.fromUrl(url));
}
if (configuration.has(CQLConfigOptions.STRING_CONFIGURATION)) {
String stringConfiguration = configuration.get(CQLConfigOptions.STRING_CONFIGURATION);
driverConfigLoadersToUse.push(DriverConfigLoader.fromString(stringConfiguration));
}
if (configuration.has(CQLConfigOptions.RESOURCE_CONFIGURATION)) {
String resourceConfigurationPath = configuration.get(CQLConfigOptions.RESOURCE_CONFIGURATION);
driverConfigLoadersToUse.push(DriverConfigLoader.fromClasspath(resourceConfigurationPath));
}
if (configuration.has(CQLConfigOptions.FILE_CONFIGURATION)) {
String fileConfigurationPath = configuration.get(CQLConfigOptions.FILE_CONFIGURATION);
driverConfigLoadersToUse.push(DriverConfigLoader.fromFile(new File(fileConfigurationPath)));
}
if (!driverConfigLoadersToUse.empty()) {
DriverConfigLoader composedDriverConfigLoader = driverConfigLoadersToUse.pop();
while (!driverConfigLoadersToUse.empty()) {
composedDriverConfigLoader = DriverConfigLoader.compose(composedDriverConfigLoader, driverConfigLoadersToUse.pop());
}
builder.withConfigLoader(composedDriverConfigLoader);
}
return builder.build();
}
use of com.datastax.oss.driver.api.core.CqlSessionBuilder in project spring-boot by spring-projects.
the class CassandraAutoConfigurationTests method cqlSessionBuildHasScopePrototype.
@Test
void cqlSessionBuildHasScopePrototype() {
this.contextRunner.run((context) -> {
CqlIdentifier keyspace = CqlIdentifier.fromCql("test");
CqlSessionBuilder firstBuilder = context.getBean(CqlSessionBuilder.class);
assertThat(firstBuilder.withKeyspace(keyspace)).hasFieldOrPropertyWithValue("keyspace", keyspace);
CqlSessionBuilder secondBuilder = context.getBean(CqlSessionBuilder.class);
assertThat(secondBuilder).hasFieldOrPropertyWithValue("keyspace", null);
});
}
use of com.datastax.oss.driver.api.core.CqlSessionBuilder in project zipkin by openzipkin.
the class SessionBuilder method buildSession.
/**
* Returns a connected session. Closes the cluster if any exception occurred.
*/
public static CqlSession buildSession(String contactPoints, String localDc, Map<DriverOption, Integer> poolingOptions, @Nullable AuthProvider authProvider, boolean useSsl) {
// Some options aren't supported by builder methods. In these cases, we use driver config
// See https://groups.google.com/a/lists.datastax.com/forum/#!topic/java-driver-user/Z8HrCDX47Q0
ProgrammaticDriverConfigLoaderBuilder config = // server, where Thread.currentThread().getContextClassLoader() returns null
DriverConfigLoader.programmaticBuilder(SessionBuilder.class.getClassLoader());
// Ported from java-driver v3 PoolingOptions.setPoolTimeoutMillis as request timeout includes that
config.withDuration(REQUEST_TIMEOUT, Duration.ofMinutes(1));
CqlSessionBuilder builder = CqlSession.builder();
builder.addContactPoints(parseContactPoints(contactPoints));
if (authProvider != null)
builder.withAuthProvider(authProvider);
// In java-driver v3, we used LatencyAwarePolicy(DCAwareRoundRobinPolicy|RoundRobinPolicy)
// where DCAwareRoundRobinPolicy was used if localDc != null
//
// In java-driver v4, the default policy is token-aware and localDc is required. Hence, we
// use the default load balancing policy
// * https://github.com/datastax/java-driver/blob/master/manual/core/load_balancing/README.md
builder.withLocalDatacenter(localDc);
config = config.withString(REQUEST_CONSISTENCY, "LOCAL_ONE");
// Pooling options changed dramatically from v3->v4. This is a close match.
poolingOptions.forEach(config::withInt);
// All Zipkin CQL writes are idempotent
config = config.withBoolean(REQUEST_DEFAULT_IDEMPOTENCE, true);
if (useSsl)
config = config.withClass(SSL_ENGINE_FACTORY_CLASS, DefaultSslEngineFactory.class);
// Log categories can enable query logging
Logger requestLogger = LoggerFactory.getLogger(RequestLogger.class);
if (requestLogger.isDebugEnabled()) {
config = config.withClass(REQUEST_TRACKER_CLASS, RequestLogger.class);
config = config.withBoolean(REQUEST_LOGGER_SUCCESS_ENABLED, true);
// Only show bodies when TRACE is enabled
config = config.withBoolean(REQUEST_LOGGER_VALUES, requestLogger.isTraceEnabled());
}
// Don't warn: ensureSchema creates the keyspace. Hence, we need to "use" it later.
config = config.withBoolean(REQUEST_WARN_IF_SET_KEYSPACE, false);
return builder.withConfigLoader(config.build()).build();
}
Aggregations