com.couchbase.client.java.Cluster Java Examples

The following examples show how to use com.couchbase.client.java.Cluster. 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: ClusterSupplier.java    From java-dcp-client with Apache License 2.0 6 votes vote down vote up
public Cluster get() {
  synchronized (this) {
    if (cluster == null) {
      env = ClusterEnvironment.builder()
          // Accommodate slow CI docker environment
          .timeoutConfig(TimeoutConfig.kvTimeout(Duration.ofSeconds(30)))
          .build();

      cluster = Cluster.connect(bootstrapHostnames,
          clusterOptions(username, password)
              .environment(env));

      // open a bucket so management API calls succeed against server versions prior to 6.5
      cluster.bucket("default");
    }
    return cluster;
  }
}
 
Example #2
Source File: KafkaCouchbaseClient.java    From kafka-connect-couchbase with Apache License 2.0 6 votes vote down vote up
public KafkaCouchbaseClient(CommonConfig config) {
  List<String> clusterAddress = config.seedNodes();
  String connectionString = String.join(",", clusterAddress);
  NetworkResolution networkResolution = NetworkResolution.valueOf(config.network());

  SecurityConfig.Builder securityConfig = SecurityConfig.builder()
      .enableTls(config.enableTls());
  if (!isNullOrEmpty(config.trustStorePath())) {
    securityConfig.trustStore(new File(config.trustStorePath()).toPath(), config.trustStorePassword().value(), Optional.empty());
  }

  env = ClusterEnvironment.builder()
      .securityConfig(securityConfig)
      .ioConfig(networkResolution(networkResolution))
      .timeoutConfig(connectTimeout(config.bootstrapTimeout()))
      .build();

  cluster = Cluster.connect(connectionString,
      clusterOptions(config.username(), config.password().value())
          .environment(env));

  bucket = cluster.bucket(config.bucket());
}
 
Example #3
Source File: CouchbaseClientTest.java    From nosql4idea with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    Cluster cluster = CouchbaseCluster.create(DefaultCouchbaseEnvironment
            .builder()
            .queryEnabled(true)
            .build());

    Bucket defaultBucket = cluster.openBucket("default");
    defaultBucket.remove("user:walter");

    JsonArray friends = JsonArray.empty()
            .add(JsonObject.empty().put("name", "Mike Ehrmantraut"))
            .add(JsonObject.empty().put("name", "Jesse Pinkman"));

    JsonObject content = JsonObject.empty()
            .put("firstname", "Walter")
            .put("lastname", "White")
            .put("age", 52)
            .put("aliases", JsonArray.from("Walt Jackson", "Mr. Mayhew", "David Lynn"))
            .put("friends", friends);
    JsonDocument walter = JsonDocument.create("user:walter", content);
    JsonDocument inserted = defaultBucket.insert(walter);

    JsonDocument foundGuy = defaultBucket.get("user:walter");
    System.out.println(foundGuy.content().toMap());


    Bucket beerBucket = cluster.openBucket("beer-sample");
    N1qlQueryResult result = beerBucket.query(N1qlQuery.simple(select("*").from(i("beer-sample")).limit(10)));

    System.out.println("Errors found: " + result.errors());

    for (N1qlQueryRow row : result.allRows()) {
        JsonObject jsonObject = row.value();
        System.out.println(jsonObject.toMap());
    }

    cluster.disconnect();
}
 
Example #4
Source File: PersonServiceImplLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@BeforeClass
public static void setupBeforeClass() {
    final Cluster cluster = CouchbaseCluster.create(MultiBucketCouchbaseConfig.NODE_LIST);
    final Bucket bucket = cluster.openBucket(MultiBucketCouchbaseConfig.DEFAULT_BUCKET_NAME, MultiBucketCouchbaseConfig.DEFAULT_BUCKET_PASSWORD);
    bucket.upsert(JsonDocument.create(johnSmithId, jsonJohnSmith));
    bucket.upsert(JsonDocument.create(foobarId, jsonFooBar));
    bucket.close();
    cluster.disconnect();
}
 
Example #5
Source File: StudentServiceImplLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@BeforeClass
public static void setupBeforeClass() {
    Cluster cluster = CouchbaseCluster.create(MultiBucketCouchbaseConfig.NODE_LIST);
    Bucket bucket = cluster.openBucket(MultiBucketCouchbaseConfig.DEFAULT_BUCKET_NAME, MultiBucketCouchbaseConfig.DEFAULT_BUCKET_PASSWORD);
    bucket.upsert(JsonDocument.create(joeCollegeId, jsonJoeCollege));
    bucket.upsert(JsonDocument.create(judyJetsonId, jsonJudyJetson));
    bucket.close();
    cluster.disconnect();
}
 
Example #6
Source File: StudentServiceLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@BeforeClass
public static void setupBeforeClass() {
    Cluster cluster = CouchbaseCluster.create(MyCouchbaseConfig.NODE_LIST);
    Bucket bucket = cluster.openBucket(MyCouchbaseConfig.BUCKET_NAME, MyCouchbaseConfig.BUCKET_PASSWORD);
    bucket.upsert(JsonDocument.create(joeCollegeId, jsonJoeCollege));
    bucket.upsert(JsonDocument.create(judyJetsonId, jsonJudyJetson));
    bucket.close();
    cluster.disconnect();
}
 
Example #7
Source File: PersonServiceLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@BeforeClass
public static void setupBeforeClass() {
    final Cluster cluster = CouchbaseCluster.create(MyCouchbaseConfig.NODE_LIST);
    final Bucket bucket = cluster.openBucket(MyCouchbaseConfig.BUCKET_NAME, MyCouchbaseConfig.BUCKET_PASSWORD);
    bucket.upsert(JsonDocument.create(johnSmithId, jsonJohnSmith));
    bucket.upsert(JsonDocument.create(foobarId, jsonFooBar));
    bucket.close();
    cluster.disconnect();
}
 
Example #8
Source File: PersonCrudServiceIntegrationTestConfig.java    From tutorials with MIT License 5 votes vote down vote up
@Bean
public Cluster cluster() {
    CouchbaseEnvironment env = DefaultCouchbaseEnvironment.builder()
      .connectTimeout(60000)
      .build();
    return CouchbaseCluster.create(env, "127.0.0.1");
}
 
Example #9
Source File: IntegrationTestConfig.java    From tutorials with MIT License 5 votes vote down vote up
@Bean
public Cluster cluster() {
    CouchbaseEnvironment env = DefaultCouchbaseEnvironment.builder()
      .connectTimeout(60000)
      .build();
    return CouchbaseCluster.create(env, "127.0.0.1");
}
 
Example #10
Source File: CouchbaseCacheDAO.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
/**
 * Initialize connection to Couchbase and open bucket where data is stored.
 */
private void createDataStoreConnection() {
  CacheDataSource dataSource = CacheConfig.getInstance().getCentralizedCacheSettings().getDataSourceConfig();
  Map<String, Object> config = dataSource.getConfig();
  List<String> hosts = ConfigUtils.getList(config.get(HOSTS));

  Cluster cluster;
  if (MapUtils.getBoolean(config, USE_CERT_BASED_AUTH)) {
    CouchbaseEnvironment env = DefaultCouchbaseEnvironment
        .builder()
        .sslEnabled(true)
        .certAuthEnabled(true)
        .dnsSrvEnabled(MapUtils.getBoolean(config, ENABLE_DNS_SRV))
        .sslKeystoreFile(MapUtils.getString(config, KEY_STORE_FILE_PATH))
        .sslKeystorePassword(MapUtils.getString(config, KEY_STORE_PASSWORD))
        .sslTruststoreFile(MapUtils.getString(config, TRUST_STORE_FILE_PATH))
        .sslTruststorePassword(MapUtils.getString(config, TRUST_STORE_PASSWORD))
        .build();

    cluster = CouchbaseCluster.create(env, CacheUtils.getBootstrapHosts(hosts));
    cluster.authenticate(CertAuthenticator.INSTANCE);
  } else {
    cluster = CouchbaseCluster.create(hosts);
    cluster.authenticate(MapUtils.getString(config, AUTH_USERNAME), MapUtils.getString(config, AUTH_PASSWORD));
  }

  this.bucket = cluster.openBucket(CacheUtils.getBucketName());
}
 
Example #11
Source File: CouchbaseClientTest.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
@Test
public void test(final MockTracer tracer) {
  final Cluster cluster = CouchbaseCluster.create(DefaultCouchbaseEnvironment.builder().connectTimeout(TimeUnit.SECONDS.toMillis(60)).build());
  final Bucket bucket = cluster.openBucket(bucketName);

  final JsonObject arthur = JsonObject.create()
    .put("name", "Arthur")
    .put("email", "[email protected]")
    .put("interests", JsonArray.from("Holy Grail", "African Swallows"));

  bucket.upsert(JsonDocument.create("u:king_arthur", arthur));
  System.out.println(bucket.get("u:king_arthur"));

  cluster.disconnect(60, TimeUnit.SECONDS);

  final List<MockSpan> spans = tracer.finishedSpans();
  assertEquals(6, spans.size());

  boolean foundCouchbaseSpan = false;
  for (final MockSpan span : spans) {
    final String component = (String)span.tags().get(Tags.COMPONENT.getKey());
    if (component != null && component.startsWith("couchbase-java-client")) {
      foundCouchbaseSpan = true;
      break;
    }
  }

  assertTrue("couchbase-java-client span not found", foundCouchbaseSpan);
}
 
Example #12
Source File: CouchbaseClient.java    From nosql4idea with Apache License 2.0 5 votes vote down vote up
public CouchbaseResult loadRecords(ServerConfiguration configuration, CouchbaseDatabase database, CouchbaseQuery couchbaseQuery) {
        Cluster cluster = CouchbaseCluster.create(DefaultCouchbaseEnvironment
                .builder()
                .queryEnabled(true)
                .build(),
                configuration.getServerUrl());
//        AuthenticationSettings authenticationSettings = configuration.getAuthenticationSettings();
//        ClusterManager clusterManager = cluster.clusterManager(authenticationSettings.getUsername(), authenticationSettings.getPassword());

        Bucket beerBucket = cluster.openBucket(database.getName(), 10, TimeUnit.SECONDS);
        N1qlQueryResult queryResult = beerBucket.query(N1qlQuery.simple(select("*").from(i(database.getName())).limit(couchbaseQuery.getLimit())));

//TODO dirty zone :(
        CouchbaseResult result = new CouchbaseResult(database.getName());
        List<JsonObject> errors = queryResult.errors();
        if (!errors.isEmpty()) {
            cluster.disconnect();
            result.addErrors(errors);
            return result;
        }

        for (N1qlQueryRow row : queryResult.allRows()) {
            result.add(row.value());
        }
        cluster.disconnect();
        return result;
    }
 
Example #13
Source File: N1qlWriter.java    From kafka-connect-couchbase with Apache License 2.0 5 votes vote down vote up
public Mono<Void> write(final Cluster cluster, final String bucketName, final JsonBinaryDocument document) {
  final JsonObject node;
  try {
    node = JsonObject.fromJson(document.content());
  } catch (IllegalArgumentException e) {
    LOGGER.warn("could not generate n1ql statement from node (not json)", e);
    return Mono.empty();
  }

  if (node.isEmpty()) {
    LOGGER.warn("could not generate n1ql statement from empty node");
    return Mono.empty();
  }

  for (String name : node.getNames()) {
    if (name.contains("`")) {
      // todo figure out how to escape backticks when generating N1QL statements.
      // For now, bail out to avoid N1QL injection.
      LOGGER.warn("could not generate n1ql statement from node with backtick (`) in field name");
      return Mono.empty();
    }
  }

  String statement = getStatement(bucketName, node);
  node.put(ID_FIELD, document.id());
  return cluster.reactive()
      .query(statement, queryOptions().parameters(node))
      .then();
}
 
Example #14
Source File: CouchbaseClientITest.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
public static void main(final String[] args) throws BucketAlreadyExistsException, InterruptedException, IOException {
  final CouchbaseMock couchbaseMock = new CouchbaseMock("localhost", 8091, 2, 1);
  final BucketConfiguration bucketConfiguration = new BucketConfiguration();
  bucketConfiguration.name = bucketName;
  bucketConfiguration.numNodes = 1;
  bucketConfiguration.numReplicas = 1;
  bucketConfiguration.password = "";
  couchbaseMock.start();
  couchbaseMock.waitForStartup();
  couchbaseMock.createBucket(bucketConfiguration);

  final Cluster cluster = CouchbaseCluster.create(DefaultCouchbaseEnvironment.builder().connectTimeout(TimeUnit.SECONDS.toMillis(60)).build());
  final Bucket bucket = cluster.openBucket(bucketName);

  final JsonObject arthur = JsonObject
    .create().put("name", "Arthur")
    .put("email", "[email protected]")
    .put("interests", JsonArray.from("Holy Grail", "African Swallows"));

  bucket.upsert(JsonDocument.create("u:king_arthur", arthur));

  System.out.println(bucket.get("u:king_arthur"));

  cluster.disconnect(60, TimeUnit.SECONDS);
  couchbaseMock.stop();

  TestUtil.checkSpan(new ComponentSpanCount("couchbase-java-client.*", 2));
}
 
Example #15
Source File: CouchbaseContainerTest.java    From testcontainers-java with MIT License 4 votes vote down vote up
@Test
public void testBasicContainerUsage() {
    // bucket_definition {
    BucketDefinition bucketDefinition = new BucketDefinition("mybucket");
    // }

    try (
        // container_definition {
        CouchbaseContainer container = new CouchbaseContainer()
            .withBucket(bucketDefinition)
        // }
    ) {
        container.start();

        // cluster_creation {
        CouchbaseEnvironment environment = DefaultCouchbaseEnvironment
            .builder()
            .bootstrapCarrierDirectPort(container.getBootstrapCarrierDirectPort())
            .bootstrapHttpDirectPort(container.getBootstrapHttpDirectPort())
            .build();

        Cluster cluster = CouchbaseCluster.create(
            environment,
            container.getHost()
        );
        // }

        try {
            // auth {
            cluster.authenticate(container.getUsername(), container.getPassword());
            // }

            Bucket bucket = cluster.openBucket(bucketDefinition.getName());

            bucket.upsert(JsonDocument.create("foo", JsonObject.empty()));

            assertTrue(bucket.exists("foo"));
            assertNotNull(cluster.clusterManager().getBucket(bucketDefinition.getName()));
        } finally {
            cluster.disconnect();
            environment.shutdown();
        }
    }
}
 
Example #16
Source File: CouchbaseBucketRegistry.java    From samza with Apache License 2.0 4 votes vote down vote up
/**
 * Helper method to open a bucket with given bucket name and cluster
 */
private Bucket openBucket(String bucketName, Cluster cluster) {
  return cluster.openBucket(bucketName);
}
 
Example #17
Source File: CodeSnippets.java    From tutorials with MIT License 4 votes vote down vote up
static Cluster loadClusterWithDefaultEnvironment() {
    return CouchbaseCluster.create("localhost");
}
 
Example #18
Source File: CodeSnippets.java    From tutorials with MIT License 4 votes vote down vote up
static Cluster loadClusterWithCustomEnvironment() {
    CouchbaseEnvironment env = DefaultCouchbaseEnvironment.builder().connectTimeout(10000).kvTimeout(3000).build();
    return CouchbaseCluster.create(env, "localhost");
}
 
Example #19
Source File: CodeSnippets.java    From tutorials with MIT License 4 votes vote down vote up
static Bucket loadDefaultBucketWithBlankPassword(Cluster cluster) {
    return cluster.openBucket();
}
 
Example #20
Source File: CodeSnippets.java    From tutorials with MIT License 4 votes vote down vote up
static Bucket loadBaeldungBucket(Cluster cluster) {
    return cluster.openBucket("baeldung", "");
}
 
Example #21
Source File: ClusterServiceImpl.java    From tutorials with MIT License 4 votes vote down vote up
@Autowired
public ClusterServiceImpl(Cluster cluster) {
    this.cluster = cluster;
}
 
Example #22
Source File: CouchbaseBucketRegistry.java    From samza with Apache License 2.0 4 votes vote down vote up
/**
 * Helper method to open a cluster given cluster nodes and environment configurations.
 */
private Cluster openCluster(List<String> clusterNodes, CouchbaseEnvironmentConfigs configs) {
  DefaultCouchbaseEnvironment.Builder envBuilder = new DefaultCouchbaseEnvironment.Builder();
  if (configs.sslEnabled != null) {
    envBuilder.sslEnabled(configs.sslEnabled);
  }
  if (configs.certAuthEnabled != null) {
    envBuilder.certAuthEnabled(configs.certAuthEnabled);
  }
  if (configs.sslKeystoreFile != null) {
    envBuilder.sslKeystoreFile(configs.sslKeystoreFile);
  }
  if (configs.sslKeystorePassword != null) {
    envBuilder.sslKeystorePassword(configs.sslKeystorePassword);
  }
  if (configs.sslTruststoreFile != null) {
    envBuilder.sslTruststoreFile(configs.sslTruststoreFile);
  }
  if (configs.sslTruststorePassword != null) {
    envBuilder.sslTruststorePassword(configs.sslTruststorePassword);
  }
  if (configs.bootstrapCarrierDirectPort != null) {
    envBuilder.bootstrapCarrierDirectPort(configs.bootstrapCarrierDirectPort);
  }
  if (configs.bootstrapCarrierSslPort != null) {
    envBuilder.bootstrapCarrierSslPort(configs.bootstrapCarrierSslPort);
  }
  if (configs.bootstrapHttpDirectPort != null) {
    envBuilder.bootstrapHttpDirectPort(configs.bootstrapHttpDirectPort);
  }
  if (configs.bootstrapHttpSslPort != null) {
    envBuilder.bootstrapHttpSslPort(configs.bootstrapHttpSslPort);
  }
  CouchbaseEnvironment env = envBuilder.build();
  Cluster cluster = CouchbaseCluster.create(env, clusterNodes);
  if (configs.sslEnabled != null && configs.sslEnabled) {
    cluster.authenticate(CertAuthenticator.INSTANCE);
  } else if (configs.username != null) {
    cluster.authenticate(configs.username, configs.password);
  } else {
    LOGGER.warn("No authentication is enabled for cluster: {}. This is not recommended except for test cases.",
        clusterNodes);
  }
  return cluster;
}
 
Example #23
Source File: KafkaCouchbaseClient.java    From kafka-connect-couchbase with Apache License 2.0 4 votes vote down vote up
public Cluster cluster() {
  return cluster;
}
 
Example #24
Source File: DocumentServiceImpl.java    From java-dcp-client with Apache License 2.0 4 votes vote down vote up
private Cluster cluster() {
  return clusterSupplier.get();
}
 
Example #25
Source File: CollectionServiceImpl.java    From java-dcp-client with Apache License 2.0 4 votes vote down vote up
private Cluster cluster() {
  return clusterSupplier.get();
}