com.datastax.driver.core.PlainTextAuthProvider Java Examples

The following examples show how to use com.datastax.driver.core.PlainTextAuthProvider. 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: CassandraTarget.java    From datacollector with Apache License 2.0 6 votes vote down vote up
private AuthProvider getAuthProvider() throws StageException {
  switch (conf.authProviderOption) {
    case NONE:
      return AuthProvider.NONE;
    case PLAINTEXT:
      return new PlainTextAuthProvider(conf.username.get(), conf.password.get());
    case DSE_PLAINTEXT:
      return new DsePlainTextAuthProvider(conf.username.get(), conf.password.get());
    case KERBEROS:
      AccessControlContext accessContext = AccessController.getContext();
      Subject subject = Subject.getSubject(accessContext);
      return DseGSSAPIAuthProvider.builder().withSubject(subject).build();
    default:
      throw new IllegalArgumentException("Unrecognized AuthProvider: " + conf.authProviderOption);
  }
}
 
Example #2
Source File: CqlConfigHelper.java    From stratio-cassandra with Apache License 2.0 6 votes vote down vote up
private static AuthProvider getClientAuthProvider(String factoryClassName, Configuration conf)
{
    try
    {
        Class<?> c = Class.forName(factoryClassName);
        if (PlainTextAuthProvider.class.equals(c))
        {
            String username = getStringSetting(USERNAME, conf).or("");
            String password = getStringSetting(PASSWORD, conf).or("");
            return (AuthProvider) c.getConstructor(String.class, String.class)
                    .newInstance(username, password);
        }
        else
        {
            return (AuthProvider) c.newInstance();
        }
    }
    catch (Exception e)
    {
        throw new RuntimeException("Failed to instantiate auth provider:" + factoryClassName, e);
    }
}
 
Example #3
Source File: CassandraConfiguration.java    From spring-cloud-stream-app-starters with Apache License 2.0 5 votes vote down vote up
@Override
protected AuthProvider getAuthProvider() {
	if (StringUtils.hasText(this.cassandraProperties.getUsername())) {
		return new PlainTextAuthProvider(this.cassandraProperties.getUsername(),
				this.cassandraProperties.getPassword());
	}
	else {
		return null;
	}
}
 
Example #4
Source File: DatastaxAuthenticationTest.java    From heroic with Apache License 2.0 5 votes vote down vote up
@Test
public void testPlain() {
    final DatastaxAuthentication a =
        new DatastaxAuthentication.Plain(Optional.of("foo"), Optional.of("bar"));
    a.accept(builder);
    verify(builder).withAuthProvider(any(PlainTextAuthProvider.class));
}
 
Example #5
Source File: CqlConfigHelper.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
public static void setUserNameAndPassword(Configuration conf, String username, String password)
{
    if (StringUtils.isNotBlank(username))
    {
        conf.set(INPUT_NATIVE_AUTH_PROVIDER, PlainTextAuthProvider.class.getName());
        conf.set(USERNAME, username);
        conf.set(PASSWORD, password);
    }
}
 
Example #6
Source File: YugabyteCloudConfig.java    From yugastore-java with Apache License 2.0 4 votes vote down vote up
@Override
protected AuthProvider getAuthProvider() {
	return new PlainTextAuthProvider(cassandraUsername, cassandraPassword);
}
 
Example #7
Source File: AppConfig.java    From spring-boot-ddd with GNU General Public License v3.0 4 votes vote down vote up
@Override
protected AuthProvider getAuthProvider() {
    return new PlainTextAuthProvider(this.cassandraProperties.getUsername(),
            this.cassandraProperties.getPassword());
}
 
Example #8
Source File: CassandraConfiguration.java    From emodb with Apache License 2.0 4 votes vote down vote up
private com.datastax.driver.core.Cluster.Builder newCqlDriverBuilder(ConnectionPoolConfiguration poolConfig,
                                                                     MetricRegistry metricRegistry) {
    performHostDiscovery(metricRegistry);

    String[] seeds = _seeds.split(",");
    List<String> contactPoints = Lists.newArrayListWithCapacity(seeds.length);

    // Each seed may be a host name or a host name and port (e.g.; "1.2.3.4" or "1.2.3.4:9160").  These need
    // to be converted into host names only.
    for (String seed : seeds) {
        HostAndPort hostAndPort = HostAndPort.fromString(seed);
        seed = hostAndPort.getHostText();
        if (hostAndPort.hasPort()) {
            if (hostAndPort.getPort() == _thriftPort) {
                _log.debug("Seed {} found using RPC port; swapping for native port {}", seed, _cqlPort);
            } else if (hostAndPort.getPort() != _cqlPort) {
                throw new IllegalArgumentException(String.format(
                        "Seed %s found with invalid port %s.  The port must match either the RPC (thrift) port %s " +
                        "or the native (CQL) port %s", seed, hostAndPort.getPort(), _thriftPort, _cqlPort));
            }
        }

        contactPoints.add(seed);
    }

    PoolingOptions poolingOptions = new PoolingOptions();
    if (poolConfig.getMaxConnectionsPerHost().or(getMaxConnectionsPerHost()).isPresent()) {
        poolingOptions.setMaxConnectionsPerHost(HostDistance.LOCAL, poolConfig.getMaxConnectionsPerHost().or(getMaxConnectionsPerHost()).get());
    }
    if (poolConfig.getCoreConnectionsPerHost().or(getCoreConnectionsPerHost()).isPresent()) {
        poolingOptions.setCoreConnectionsPerHost(HostDistance.LOCAL, poolConfig.getCoreConnectionsPerHost().or(getCoreConnectionsPerHost()).get());
    }

    SocketOptions socketOptions = new SocketOptions();
    if (poolConfig.getConnectTimeout().or(getConnectTimeout()).isPresent()) {
        socketOptions.setConnectTimeoutMillis(poolConfig.getConnectTimeout().or(getConnectTimeout()).get());
    }
    if (poolConfig.getSocketTimeout().or(getSocketTimeout()).isPresent()) {
        socketOptions.setReadTimeoutMillis(poolConfig.getSocketTimeout().or(getSocketTimeout()).get());
    }

    AuthProvider authProvider = _authenticationCredentials != null
            ? new PlainTextAuthProvider(_authenticationCredentials.getUsername(), _authenticationCredentials.getPassword())
            : AuthProvider.NONE;

    return com.datastax.driver.core.Cluster.builder()
            .addContactPoints(contactPoints.toArray(new String[contactPoints.size()]))
            .withPort(_cqlPort)
            .withPoolingOptions(poolingOptions)
            .withSocketOptions(socketOptions)
            .withRetryPolicy(Policies.defaultRetryPolicy())
            .withAuthProvider(authProvider);
}
 
Example #9
Source File: CassandraIO.java    From beam with Apache License 2.0 4 votes vote down vote up
/** Get a Cassandra cluster using hosts and port. */
private static Cluster getCluster(
    ValueProvider<List<String>> hosts,
    ValueProvider<Integer> port,
    ValueProvider<String> username,
    ValueProvider<String> password,
    ValueProvider<String> localDc,
    ValueProvider<String> consistencyLevel,
    ValueProvider<Integer> connectTimeout,
    ValueProvider<Integer> readTimeout) {

  Cluster.Builder builder =
      Cluster.builder().addContactPoints(hosts.get().toArray(new String[0])).withPort(port.get());

  if (username != null) {
    builder.withAuthProvider(new PlainTextAuthProvider(username.get(), password.get()));
  }

  DCAwareRoundRobinPolicy.Builder dcAwarePolicyBuilder = new DCAwareRoundRobinPolicy.Builder();
  if (localDc != null) {
    dcAwarePolicyBuilder.withLocalDc(localDc.get());
  }

  builder.withLoadBalancingPolicy(new TokenAwarePolicy(dcAwarePolicyBuilder.build()));

  if (consistencyLevel != null) {
    builder.withQueryOptions(
        new QueryOptions().setConsistencyLevel(ConsistencyLevel.valueOf(consistencyLevel.get())));
  }

  SocketOptions socketOptions = new SocketOptions();

  builder.withSocketOptions(socketOptions);

  if (connectTimeout != null) {
    socketOptions.setConnectTimeoutMillis(connectTimeout.get());
  }

  if (readTimeout != null) {
    socketOptions.setReadTimeoutMillis(readTimeout.get());
  }

  return builder.build();
}
 
Example #10
Source File: DatastaxAuthentication.java    From heroic with Apache License 2.0 4 votes vote down vote up
@Override
public void accept(final Builder builder) {
    builder.withAuthProvider(new PlainTextAuthProvider(username, password));
}
 
Example #11
Source File: PlainTextAuthProviderFactory.java    From dropwizard-cassandra with Apache License 2.0 4 votes vote down vote up
@Override
public AuthProvider build() {
    return new PlainTextAuthProvider(username, password);
}
 
Example #12
Source File: CassandraCluster.java    From monasca-persister with Apache License 2.0 4 votes vote down vote up
@Inject
public CassandraCluster(final PersisterConfig config) {

  this.dbConfig = config.getCassandraDbConfiguration();

  QueryOptions qo = new QueryOptions();
  qo.setConsistencyLevel(ConsistencyLevel.valueOf(dbConfig.getConsistencyLevel()));
  qo.setDefaultIdempotence(true);

  String[] contactPoints = dbConfig.getContactPoints();
  int retries = dbConfig.getMaxWriteRetries();
  Builder builder = Cluster.builder().addContactPoints(contactPoints).withPort(dbConfig.getPort());
  builder
      .withSocketOptions(new SocketOptions().setConnectTimeoutMillis(dbConfig.getConnectionTimeout())
          .setReadTimeoutMillis(dbConfig.getReadTimeout()));
  builder.withQueryOptions(qo).withRetryPolicy(new MonascaRetryPolicy(retries, retries, retries));

  lbPolicy = new TokenAwarePolicy(
      DCAwareRoundRobinPolicy.builder().withLocalDc(dbConfig.getLocalDataCenter()).build());
  builder.withLoadBalancingPolicy(lbPolicy);

  String user = dbConfig.getUser();
  if (user != null && !user.isEmpty()) {
    builder.withAuthProvider(new PlainTextAuthProvider(dbConfig.getUser(), dbConfig.getPassword()));
  }
  cluster = builder.build();

  PoolingOptions poolingOptions = cluster.getConfiguration().getPoolingOptions();

  poolingOptions.setConnectionsPerHost(HostDistance.LOCAL, dbConfig.getMaxConnections(),
      dbConfig.getMaxConnections()).setConnectionsPerHost(HostDistance.REMOTE,
          dbConfig.getMaxConnections(), dbConfig.getMaxConnections());

  poolingOptions.setMaxRequestsPerConnection(HostDistance.LOCAL, dbConfig.getMaxRequests())
      .setMaxRequestsPerConnection(HostDistance.REMOTE, dbConfig.getMaxRequests());

  metricsSession = cluster.connect(dbConfig.getKeySpace());

  measurementInsertStmt = metricsSession.prepare(MEASUREMENT_INSERT_CQL).setIdempotent(true);
  // TODO: Remove update statements, TTL issues
  measurementUpdateStmt = metricsSession.prepare(MEASUREMENT_UPDATE_CQL).setIdempotent(true);
  metricInsertStmt = metricsSession.prepare(METRICS_INSERT_CQL).setIdempotent(true);
  dimensionStmt = metricsSession.prepare(DIMENSION_INSERT_CQL).setIdempotent(true);
  dimensionMetricStmt = metricsSession.prepare(DIMENSION_METRIC_INSERT_CQL).setIdempotent(true);
  metricDimensionStmt = metricsSession.prepare(METRIC_DIMENSION_INSERT_CQL).setIdempotent(true);

  retrieveMetricIdStmt = metricsSession.prepare(RETRIEVE_METRIC_ID_CQL).setIdempotent(true);
  retrieveMetricDimensionStmt = metricsSession.prepare(RETRIEVE_METRIC_DIMENSION_CQL)
      .setIdempotent(true);

  alarmsSession = cluster.connect(dbConfig.getKeySpace());

  alarmHistoryInsertStmt = alarmsSession.prepare(INSERT_ALARM_STATE_HISTORY_SQL).setIdempotent(true);

  metricIdCache = CacheBuilder.newBuilder()
      .maximumSize(config.getCassandraDbConfiguration().getDefinitionMaxCacheSize()).build();

  dimensionCache = CacheBuilder.newBuilder()
      .maximumSize(config.getCassandraDbConfiguration().getDefinitionMaxCacheSize()).build();

  metricDimensionCache = CacheBuilder.newBuilder()
      .maximumSize(config.getCassandraDbConfiguration().getDefinitionMaxCacheSize()).build();

  logger.info("loading cached definitions from db");

  ExecutorService executor = Executors.newFixedThreadPool(250);

  //a majority of the ids are for metrics not actively receiving msgs anymore
  //loadMetricIdCache(executor);

  loadDimensionCache();

  loadMetricDimensionCache(executor);

  executor.shutdown();
}
 
Example #13
Source File: CassandraClusterCreatorTest.java    From spring-cloud-connectors with Apache License 2.0 3 votes vote down vote up
@Test
public void shouldCreateClusterWithAuthentication() throws Exception {

	CassandraServiceInfo info = new CassandraServiceInfo("local",
			Collections.singletonList("127.0.0.1"), 9142, "walter", "white");

	Cluster cluster = creator.create(info, null);

	Configuration configuration = cluster.getConfiguration();

	assertThat(configuration.getProtocolOptions().getAuthProvider(),
			is(instanceOf(PlainTextAuthProvider.class)));
}