Java Code Examples for com.datastax.oss.driver.api.core.CqlSessionBuilder#build()

The following examples show how to use com.datastax.oss.driver.api.core.CqlSessionBuilder#build() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CassandraManager.java    From dynamo-cassandra-proxy with Apache License 2.0 5 votes vote down vote up
public void start() {
    logger.info("Contact points {}", config.getContactPoints());

    CqlSessionBuilder builder = CqlSession.builder()
            .addContactPoints(Arrays.stream(config.getContactPoints().split(","))
                    .map(s -> new InetSocketAddress(s, config.getCqlPort()))
                    .collect(Collectors.toList()))
            .withLocalDatacenter(config.getLocalDC());

    if (config.getCqlUserName() != null)
        builder.withAuthCredentials(config.getCqlUserName(), config.getCqlPassword());

    if (config.isDockerCassandra()) {
        logger.info("Docker cassandra enabled in the yaml.");
        logger.info("Attempting to stand up container.");
        DockerHelper dh = new DockerHelper();
        dh.startDSE();

        //TODO
        try {
            Thread.sleep(60000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

    session = builder.build();


    logger.info("Preparing statements for " + CassandraManager.class.getSimpleName());
    stmts = new CassandraStatements.Prepared(session, config.getKeyspaceName(), config.getReplicationStrategy());

    refreshSchema();
}
 
Example 2
Source File: CassandraDataStoreConnector.java    From egeria with Apache License 2.0 5 votes vote down vote up
/**
 * Set up the Cassandra Cluster Connection with schema change listener to track the metadata changes
 *
 * @param schemaChangeListener the schema change listener
 */
public void startCassandraConnection(SchemaChangeListener schemaChangeListener) {

    String actionDescription = "start Cassandra Data Store Connection";
    try {
        CqlSessionBuilder builder = CqlSession.builder();
        builder.addContactPoint(new InetSocketAddress(serverAddresses, Integer.valueOf(port)));
        builder.withSchemaChangeListener(schemaChangeListener);
        builder.withAuthCredentials(username, password);
        this.cqlSession = builder.build();

    } catch (ExceptionInInitializerError e) {
        auditLog = CassandraDataStoreAuditCode.CONNECTOR_SERVER_CONNECTION_ERROR;
        omrsAuditLog.logRecord(actionDescription,
                auditLog.getLogMessageId(),
                auditLog.getSeverity(),
                auditLog.getFormattedLogMessage(),
                null,
                auditLog.getSystemAction(),
                auditLog.getUserAction());
    }
    auditLog = CassandraDataStoreAuditCode.CONNECTOR_INITIALIZED;
    omrsAuditLog.logRecord(actionDescription,
            auditLog.getLogMessageId(),
            auditLog.getSeverity(),
            auditLog.getFormattedLogMessage(),
            null,
            auditLog.getSystemAction(),
            auditLog.getUserAction());
}
 
Example 3
Source File: CassandraConnector.java    From tutorials with MIT License 5 votes vote down vote up
public void connect(final String node, final Integer port, final String dataCenter) {
    CqlSessionBuilder builder = CqlSession.builder();
    builder.addContactPoint(new InetSocketAddress(node, port));
    builder.withLocalDatacenter(dataCenter);

    session = builder.build();
}
 
Example 4
Source File: CqlSessionCassandraConnectionFactory.java    From embedded-cassandra with Apache License 2.0 4 votes vote down vote up
private CqlSession createSession(Cassandra cassandra) {
	ProgrammaticDriverConfigLoaderBuilder driverBuilder = DriverConfigLoader.programmaticBuilder()
			.withDuration(DefaultDriverOption.REQUEST_TIMEOUT, Duration.ofSeconds(30))
			.withDuration(DefaultDriverOption.CONNECTION_INIT_QUERY_TIMEOUT, Duration.ofSeconds(3));
	String username = getUsername();
	String password = getPassword();
	if (username != null && password != null) {
		driverBuilder.withString(DefaultDriverOption.AUTH_PROVIDER_USER_NAME, username)
				.withString(DefaultDriverOption.AUTH_PROVIDER_PASSWORD, password)
				.withClass(DefaultDriverOption.AUTH_PROVIDER_CLASS, PlainTextAuthProvider.class);
	}
	if (isSslEnabled()) {
		driverBuilder.withBoolean(DefaultDriverOption.SSL_HOSTNAME_VALIDATION, isHostnameValidation())
				.withClass(DefaultDriverOption.SSL_ENGINE_FACTORY_CLASS, DefaultSslEngineFactory.class);
		List<String> cipherSuites = getCipherSuites();
		if (!cipherSuites.isEmpty()) {
			driverBuilder.withStringList(DefaultDriverOption.SSL_CIPHER_SUITES, new ArrayList<>(cipherSuites));
		}
		Resource truststore = getTruststore();
		if (truststore != null) {
			driverBuilder.withString(DefaultDriverOption.SSL_TRUSTSTORE_PATH, getPath(truststore).toString());
		}
		String truststorePassword = getTruststorePassword();
		if (truststorePassword != null) {
			driverBuilder.withString(DefaultDriverOption.SSL_TRUSTSTORE_PASSWORD, truststorePassword);
		}
		Resource keystore = getKeystore();
		if (keystore != null) {
			driverBuilder.withString(DefaultDriverOption.SSL_KEYSTORE_PATH, getPath(keystore).toString());
		}
		String keystorePassword = getKeystorePassword();
		if (keystorePassword != null) {
			driverBuilder.withString(DefaultDriverOption.SSL_KEYSTORE_PASSWORD, keystorePassword);
		}
	}
	List<Consumer<? super ProgrammaticDriverConfigLoaderBuilder>> driverConfigLoaderBuilderCustomizers =
			getDriverConfigLoaderBuilderCustomizers();
	driverConfigLoaderBuilderCustomizers.forEach(customizer -> customizer.accept(driverBuilder));
	int port = cassandra.getPort();
	int sslPort = cassandra.getSslPort();
	InetSocketAddress contactPoint = new InetSocketAddress(cassandra.getAddress(),
			(isSslEnabled() && sslPort != -1) ? sslPort : port);
	CqlSessionBuilder sessionBuilder = CqlSession.builder().addContactPoint(contactPoint)
			.withConfigLoader(driverBuilder.build());
	String localDataCenter = getLocalDataCenter();
	if (localDataCenter != null) {
		sessionBuilder.withLocalDatacenter(localDataCenter);
	}
	List<TypeCodec<?>> typeCodecs = getTypeCodecs();
	if (!typeCodecs.isEmpty()) {
		sessionBuilder.addTypeCodecs(typeCodecs.toArray(new TypeCodec[0]));
	}
	List<Consumer<? super CqlSessionBuilder>> sessionBuilderCustomizers = getSessionBuilderCustomizers();
	sessionBuilderCustomizers.forEach(customizer -> customizer.accept(sessionBuilder));
	return sessionBuilder.build();
}
 
Example 5
Source File: CQLStoreManager.java    From grakn with GNU Affero General Public License v3.0 4 votes vote down vote up
private CqlSession initialiseSession() throws PermanentBackendException {
    Configuration configuration = getStorageConfig();
    List<InetSocketAddress> contactPoints;
    String[] hostnames = configuration.get(STORAGE_HOSTS);
    int port = configuration.has(STORAGE_PORT) ? configuration.get(STORAGE_PORT) : DEFAULT_PORT;
    try {
        contactPoints = Array.of(hostnames)
                .map(hostName -> hostName.split(":"))
                .map(array -> Tuple.of(array[0], array.length == 2 ? Integer.parseInt(array[1]) : port))
                .map(tuple -> new InetSocketAddress(tuple._1, tuple._2))
                .toJavaList();
    } catch (SecurityException | ArrayIndexOutOfBoundsException | NumberFormatException e) {
        throw new PermanentBackendException("Error initialising cluster contact points", e);
    }

    CqlSessionBuilder builder = CqlSession.builder()
            .addContactPoints(contactPoints)
            .withLocalDatacenter(configuration.get(LOCAL_DATACENTER));

    ProgrammaticDriverConfigLoaderBuilder configLoaderBuilder = DriverConfigLoader.programmaticBuilder();

    configLoaderBuilder.withString(DefaultDriverOption.SESSION_NAME, configuration.get(SESSION_NAME));
    configLoaderBuilder.withDuration(DefaultDriverOption.REQUEST_TIMEOUT, configuration.get(CONNECTION_TIMEOUT));

    if (configuration.get(PROTOCOL_VERSION) != 0) {
        configLoaderBuilder.withInt(DefaultDriverOption.PROTOCOL_VERSION, configuration.get(PROTOCOL_VERSION));
    }

    if (configuration.has(AUTH_USERNAME) && configuration.has(AUTH_PASSWORD)) {
        configLoaderBuilder
                .withClass(DefaultDriverOption.AUTH_PROVIDER_CLASS, PlainTextAuthProvider.class)
                .withString(DefaultDriverOption.AUTH_PROVIDER_USER_NAME, configuration.get(AUTH_USERNAME))
                .withString(DefaultDriverOption.AUTH_PROVIDER_PASSWORD, configuration.get(AUTH_PASSWORD));
    }

    if (configuration.get(SSL_ENABLED)) {
        configLoaderBuilder
                .withClass(DefaultDriverOption.SSL_ENGINE_FACTORY_CLASS, DefaultSslEngineFactory.class)
                .withString(DefaultDriverOption.SSL_TRUSTSTORE_PATH, configuration.get(SSL_TRUSTSTORE_LOCATION))
                .withString(DefaultDriverOption.SSL_TRUSTSTORE_PASSWORD, configuration.get(SSL_TRUSTSTORE_PASSWORD));
    }

    configLoaderBuilder.withInt(DefaultDriverOption.CONNECTION_POOL_LOCAL_SIZE, configuration.get(LOCAL_MAX_CONNECTIONS_PER_HOST));
    configLoaderBuilder.withInt(DefaultDriverOption.CONNECTION_POOL_REMOTE_SIZE, configuration.get(REMOTE_MAX_CONNECTIONS_PER_HOST));
    configLoaderBuilder.withInt(DefaultDriverOption.CONNECTION_MAX_REQUESTS, configuration.get(MAX_REQUESTS_PER_CONNECTION));

    // Keep to 0 for the time being: https://groups.google.com/a/lists.datastax.com/forum/#!topic/java-driver-user/Bc0gQuOVVL0
    // Ideally we want to batch all tables initialisations to happen together when opening a new keyspace
    configLoaderBuilder.withInt(DefaultDriverOption.METADATA_SCHEMA_WINDOW, 0);

    // The following sets the size of Netty ThreadPool executor used by Cassandra driver:
    // https://docs.datastax.com/en/developer/java-driver/4.0/manual/core/async/#threading-model
    configLoaderBuilder.withInt(DefaultDriverOption.NETTY_IO_SIZE, 0); // size of threadpool scales with number of available CPUs when set to 0
    configLoaderBuilder.withInt(DefaultDriverOption.NETTY_ADMIN_SIZE, 0); // size of threadpool scales with number of available CPUs when set to 0


    // Keep the following values to 0 so that when we close the session we don't have to wait for the
    // so called "quiet period", setting this to a different value will slow down Graph.close()
    configLoaderBuilder.withInt(DefaultDriverOption.NETTY_ADMIN_SHUTDOWN_QUIET_PERIOD, 0);
    configLoaderBuilder.withInt(DefaultDriverOption.NETTY_IO_SHUTDOWN_QUIET_PERIOD, 0);

    builder.withConfigLoader(configLoaderBuilder.build());

    return builder.build();
}