Java Code Examples for com.couchbase.client.java.CouchbaseCluster#create()

The following examples show how to use com.couchbase.client.java.CouchbaseCluster#create() . 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: CouchbaseLockProviderIntegrationTest.java    From ShedLock with Apache License 2.0 6 votes vote down vote up
@BeforeAll
public static void startCouchbase () {
    container = new CouchbaseContainer().withBucket(new BucketDefinition(BUCKET_NAME));
    container.start();

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

    cluster = CouchbaseCluster.create(
        environment,
        container.getContainerIpAddress()
    );

    cluster.authenticate(container.getUsername(), container.getPassword());

    bucket = cluster.openBucket(BUCKET_NAME);
}
 
Example 2
Source File: CouchbaseInputTestIT.java    From components with Apache License 2.0 6 votes vote down vote up
private void populateBucket() {
    CouchbaseEnvironment env = DefaultCouchbaseEnvironment
            .builder()
            .socketConnectTimeout(60000)
            .connectTimeout(60000)
            .keepAliveInterval(60000)
            .keyValueServiceConfig(KeyValueServiceConfig.create(60)) // If skip this config, we may get TimeoutException https://forums.couchbase.com/t/kv-upsert-throwing-timeoutexception-couchbase-4-5/9399
            .build();
    CouchbaseCluster cluster = CouchbaseCluster.create(env, bootstrapNodes);
    Bucket bucket = cluster.openBucket(bucketName, password);
    LOGGER.info("Connected to bucket - " + bucketName);
    assertTrue(bucket.bucketManager().flush());
    JsonDocument document = JsonDocument.create("foo", JsonObject.create().put("bar", 42));
    bucket.upsert(document, PersistTo.MASTER);
    bucket.close();
    LOGGER.info("Bucket is closed after upserting data");
    if (cluster != null) {
        cluster.disconnect();
    }
}
 
Example 3
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 4
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 5
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 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: 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 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: CouchbaseTestServer.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
@Test
public static void testServer()
    throws InterruptedException, IOException {
  CouchbaseTestServer couchbaseTestServer = new CouchbaseTestServer(TestUtils.findFreePort());
  couchbaseTestServer.start();

  int port = couchbaseTestServer.getPort();
  int serverPort = couchbaseTestServer.getServerPort();



  try {
    CouchbaseEnvironment cbEnv = DefaultCouchbaseEnvironment.builder().bootstrapHttpEnabled(true)
        .bootstrapHttpDirectPort(port)
        .bootstrapCarrierDirectPort(serverPort)
        .connectTimeout(TimeUnit.SECONDS.toMillis(15))
        .bootstrapCarrierEnabled(true).build();
    CouchbaseCluster cbCluster = CouchbaseCluster.create(cbEnv, "localhost");
    Bucket bucket = cbCluster.openBucket("default","");
    try {
      JsonObject content = JsonObject.empty().put("name", "Michael");
      JsonDocument doc = JsonDocument.create("docId", content);
      JsonDocument inserted = bucket.insert(doc);
    }
    catch (Exception e)
    {
      Assert.fail("Should not throw exception on insert", e);
    }
  }
  finally
  {
    couchbaseTestServer.stop();
  }
}
 
Example 10
Source File: CouchbaseWriter.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
public CouchbaseWriter(CouchbaseEnvironment couchbaseEnvironment, Config config) {

    List<String> hosts = ConfigUtils.getStringList(config, CouchbaseWriterConfigurationKeys.BOOTSTRAP_SERVERS);
    boolean usesCertAuth = ConfigUtils.getBoolean(config, CouchbaseWriterConfigurationKeys.CERT_AUTH_ENABLED, false);
    String password = ConfigUtils.getString(config, CouchbaseWriterConfigurationKeys.PASSWORD, "");

    log.info("Using hosts hosts: {}", hosts.stream().collect(Collectors.joining(",")));

    _documentTTL = ConfigUtils.getInt(config, CouchbaseWriterConfigurationKeys.DOCUMENT_TTL, 0);
    _documentTTLTimeUnits =
        ConfigUtils.getTimeUnit(config, CouchbaseWriterConfigurationKeys.DOCUMENT_TTL_UNIT, CouchbaseWriterConfigurationKeys.DOCUMENT_TTL_UNIT_DEFAULT);
    _documentTTLOriginField =
        ConfigUtils.getString(config, CouchbaseWriterConfigurationKeys.DOCUMENT_TTL_ORIGIN_FIELD, null);
    _documentTTLOriginUnits =
        ConfigUtils.getTimeUnit(config, CouchbaseWriterConfigurationKeys.DOCUMENT_TTL_ORIGIN_FIELD_UNITS,
            CouchbaseWriterConfigurationKeys.DOCUMENT_TTL_ORIGIN_FIELD_UNITS_DEFAULT);

    String bucketName = ConfigUtils.getString(config, CouchbaseWriterConfigurationKeys.BUCKET,
        CouchbaseWriterConfigurationKeys.BUCKET_DEFAULT);

    _cluster = CouchbaseCluster.create(couchbaseEnvironment, hosts);

    if (usesCertAuth) {
      _cluster.authenticate(CertAuthenticator.INSTANCE);
      _bucket = _cluster.openBucket(bucketName, Collections.singletonList(_tupleDocumentTranscoder));
    } else if (password.isEmpty()) {
      _bucket = _cluster.openBucket(bucketName, Collections.singletonList(_tupleDocumentTranscoder));
    } else {
      _bucket = _cluster.openBucket(bucketName, password, Collections.singletonList(_tupleDocumentTranscoder));
    }
    _operationTimeout = ConfigUtils.getLong(config, CouchbaseWriterConfigurationKeys.OPERATION_TIMEOUT_MILLIS,
        CouchbaseWriterConfigurationKeys.OPERATION_TIMEOUT_DEFAULT);
    _operationTimeunit = TimeUnit.MILLISECONDS;

    _defaultWriteResponseMapper = new GenericWriteResponseWrapper<>();

    log.info("Couchbase writer configured with: hosts: {}, bucketName: {}, operationTimeoutInMillis: {}", hosts,
        bucketName, _operationTimeout);
  }
 
Example 11
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 12
Source File: TestCouchbaseRemoteTableEndToEnd.java    From samza with Apache License 2.0 5 votes vote down vote up
protected void initClient() {
  couchbaseEnvironment = DefaultCouchbaseEnvironment.builder()
      .bootstrapCarrierDirectPort(couchbaseMock.getCarrierPort("inputBucket"))
      .bootstrapHttpDirectPort(couchbaseMock.getHttpPort())
      .build();
  cluster = CouchbaseCluster.create(couchbaseEnvironment, "couchbase://127.0.0.1");
}
 
Example 13
Source File: HelloCouchbaseLambda.java    From serverless with Apache License 2.0 5 votes vote down vote up
public CouchbaseCluster getCluster() {
    if (null == cluster) {
        logger.log("env: " + System.getenv("COUCHBASE_HOST"));
        cluster = CouchbaseCluster.create(System.getenv("COUCHBASE_HOST"));
    }
    return cluster;
}
 
Example 14
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 15
Source File: ClusterServiceImpl.java    From tutorials with MIT License 4 votes vote down vote up
@PostConstruct
private void init() {
    CouchbaseEnvironment env = DefaultCouchbaseEnvironment.create();
    cluster = CouchbaseCluster.create(env, "localhost");
}
 
Example 16
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 17
Source File: CouchbaseDriver.java    From hazelcast-simulator with Apache License 2.0 4 votes vote down vote up
@Override
public void startVendorInstance() throws Exception {
    String[] nodes = get("nodes").split(",");
    this.cluster = CouchbaseCluster.create(nodes);
}
 
Example 18
Source File: ClusterServiceImpl.java    From tutorials with MIT License 4 votes vote down vote up
@PostConstruct
private void init() {
    CouchbaseEnvironment env = DefaultCouchbaseEnvironment.create();
    cluster = CouchbaseCluster.create(env, "localhost");
}
 
Example 19
Source File: CodeSnippets.java    From tutorials with MIT License 4 votes vote down vote up
static Cluster loadClusterWithDefaultEnvironment() {
    return CouchbaseCluster.create("localhost");
}
 
Example 20
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");
}