Search in sources :

Example 1 with CqlSessionBuilder

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;
}
Also used : CqlSessionBuilder(com.datastax.oss.driver.api.core.CqlSessionBuilder) Scope(org.springframework.context.annotation.Scope) ConditionalOnMissingBean(org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean) ConditionalOnMissingBean(org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean) Bean(org.springframework.context.annotation.Bean)

Example 2 with CqlSessionBuilder

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);
}
Also used : InetSocketAddress(java.net.InetSocketAddress) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) SSLContext(javax.net.ssl.SSLContext) KeyStore(java.security.KeyStore) CqlSessionBuilder(com.datastax.oss.driver.api.core.CqlSessionBuilder) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) DriverConfigLoader(com.datastax.oss.driver.api.core.config.DriverConfigLoader) HashMap(java.util.HashMap) Map(java.util.Map)

Example 3 with CqlSessionBuilder

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();
}
Also used : MalformedURLException(java.net.MalformedURLException) CqlSessionBuilder(com.datastax.oss.driver.api.core.CqlSessionBuilder) PermanentBackendException(org.janusgraph.diskstorage.PermanentBackendException) ArrayList(java.util.ArrayList) DriverConfigLoader(com.datastax.oss.driver.api.core.config.DriverConfigLoader) File(java.io.File) URL(java.net.URL) Stack(java.util.Stack)

Example 4 with CqlSessionBuilder

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);
    });
}
Also used : CqlSessionBuilder(com.datastax.oss.driver.api.core.CqlSessionBuilder) CqlIdentifier(com.datastax.oss.driver.api.core.CqlIdentifier) Test(org.junit.jupiter.api.Test)

Example 5 with CqlSessionBuilder

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();
}
Also used : CqlSessionBuilder(com.datastax.oss.driver.api.core.CqlSessionBuilder) RequestLogger(com.datastax.oss.driver.internal.core.tracker.RequestLogger) CqlSessionBuilder(com.datastax.oss.driver.api.core.CqlSessionBuilder) ProgrammaticDriverConfigLoaderBuilder(com.datastax.oss.driver.api.core.config.ProgrammaticDriverConfigLoaderBuilder) RequestLogger(com.datastax.oss.driver.internal.core.tracker.RequestLogger) Logger(org.slf4j.Logger)

Aggregations

CqlSessionBuilder (com.datastax.oss.driver.api.core.CqlSessionBuilder)5 DriverConfigLoader (com.datastax.oss.driver.api.core.config.DriverConfigLoader)2 ArrayList (java.util.ArrayList)2 CqlIdentifier (com.datastax.oss.driver.api.core.CqlIdentifier)1 ProgrammaticDriverConfigLoaderBuilder (com.datastax.oss.driver.api.core.config.ProgrammaticDriverConfigLoaderBuilder)1 RequestLogger (com.datastax.oss.driver.internal.core.tracker.RequestLogger)1 File (java.io.File)1 InputStream (java.io.InputStream)1 InetSocketAddress (java.net.InetSocketAddress)1 MalformedURLException (java.net.MalformedURLException)1 URL (java.net.URL)1 KeyStore (java.security.KeyStore)1 HashMap (java.util.HashMap)1 Map (java.util.Map)1 Stack (java.util.Stack)1 SSLContext (javax.net.ssl.SSLContext)1 TrustManagerFactory (javax.net.ssl.TrustManagerFactory)1 PermanentBackendException (org.janusgraph.diskstorage.PermanentBackendException)1 Test (org.junit.jupiter.api.Test)1 Logger (org.slf4j.Logger)1