com.couchbase.client.java.CouchbaseCluster Java Examples

The following examples show how to use com.couchbase.client.java.CouchbaseCluster. 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: 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 #2
Source File: CouchbaseClusterService.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Establish a connection to a Couchbase cluster.
 * @param context the configuration context
 * @throws InitializationException if unable to connect a Couchbase cluster
 */
@OnEnabled
public void onConfigured(final ConfigurationContext context) throws InitializationException {

    for(PropertyDescriptor p : context.getProperties().keySet()){
        if(p.isDynamic() && p.getName().startsWith(DYNAMIC_PROP_BUCKET_PASSWORD)){
            String bucketName = p.getName().substring(DYNAMIC_PROP_BUCKET_PASSWORD.length());
            String password = context.getProperty(p).getValue();
            bucketPasswords.put(bucketName, password);
        }
    }
    try {
        cluster = CouchbaseCluster.fromConnectionString(context.getProperty(CONNECTION_STRING).getValue());
    } catch(CouchbaseException e) {
        throw new InitializationException(e);
    }
}
 
Example #3
Source File: CouchbaseClient.java    From nosql4idea with Apache License 2.0 6 votes vote down vote up
@Override
public void connect(ServerConfiguration serverConfiguration) {
    CouchbaseCluster cluster = CouchbaseCluster.create(serverConfiguration.getServerUrl());
    String userDatabase = serverConfiguration.getUserDatabase();
    Bucket bucket = null;
    try {
        if (StringUtils.isEmpty(userDatabase)) {
            bucket = cluster.openBucket();
        } else {
            bucket = cluster.openBucket(userDatabase);
        }

    } catch (Exception ex) {
        throw new ConfigurationException(ex);
    } finally {
        if (bucket != null) {
            bucket.close();
        }
        cluster.disconnect();
    }

}
 
Example #4
Source File: TestCouchbaseBucketRegistry.java    From samza with Apache License 2.0 6 votes vote down vote up
/**
 * This unit test simulates 10 tasks using the same bucket. Each task will call registry.getBucket once. Then
 * each task will also call registry.closeBucket once. After that, registry.closeBucket should return false if we
 * close the bucket one more time. And the bucket should have already been closed.
 */
@Test
public void testCloseBucket() {
  String bucketName = "bucket";
  List<String> clusterNodes = Arrays.asList("cluster");
  CouchbaseEnvironmentConfigs configs = new CouchbaseEnvironmentConfigs();
  CouchbaseCluster cluster = mock(CouchbaseCluster.class);
  Bucket bucket = mock(Bucket.class);
  when(bucket.close()).thenReturn(true).thenReturn(false);
  when(cluster.openBucket(bucketName)).thenReturn(bucket);
  when(cluster.disconnect()).thenReturn(true).thenReturn(false);
  mockStatic(CouchbaseCluster.class);
  when(CouchbaseCluster.create(any(CouchbaseEnvironment.class), eq(clusterNodes))).thenReturn(cluster);
  CouchbaseBucketRegistry registry = new CouchbaseBucketRegistry();
  int numOfThreads = 10;
  for (int i = 0; i < numOfThreads; i++) {
    registry.getBucket(bucketName, clusterNodes, configs);
  }
  for (int i = 0; i < numOfThreads; i++) {
    assertTrue(registry.closeBucket(bucketName, clusterNodes));
  }
  // Close one more time. Should return false.
  assertFalse(registry.closeBucket(bucketName, clusterNodes));
  // Bucket should has been closed
  assertFalse(bucket.close());
}
 
Example #5
Source File: CouchbaseClusterService.java    From nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Establish a connection to a Couchbase cluster.
 * @param context the configuration context
 * @throws InitializationException if unable to connect a Couchbase cluster
 */
@OnEnabled
public void onConfigured(final ConfigurationContext context) throws InitializationException {

    bucketPasswords = new HashMap<>();
    for(PropertyDescriptor p : context.getProperties().keySet()){
        if(p.isDynamic() && p.getName().startsWith(DYNAMIC_PROP_BUCKET_PASSWORD)){
            String bucketName = p.getName().substring(DYNAMIC_PROP_BUCKET_PASSWORD.length());
            String password = context.getProperty(p).evaluateAttributeExpressions().getValue();
            bucketPasswords.put(bucketName, password);
        }
    }

    final String userName = context.getProperty(USER_NAME).evaluateAttributeExpressions().getValue();
    final String userPassword = context.getProperty(USER_PASSWORD).evaluateAttributeExpressions().getValue();

    try {
        cluster = CouchbaseCluster.fromConnectionString(context.getProperty(CONNECTION_STRING).evaluateAttributeExpressions().getValue());
        if (!StringUtils.isEmpty(userName) && !StringUtils.isEmpty(userPassword)) {
            cluster.authenticate(userName, userPassword);
        }
    } catch(CouchbaseException e) {
        throw new InitializationException(e);
    }
}
 
Example #6
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 #7
Source File: TestCouchbaseBucketRegistry.java    From samza with Apache License 2.0 6 votes vote down vote up
/**
 * This unit test uses CouchbaseBucketRegistry to register two mocked buckets with same name but in different clusters.
 * Calling registry.getBucket with same bucketName but different clusterNodes should return different Bucket instances.
 */
@Test
public void testOpenSameBucketNameFromDifferentClusters() {
  String bucketName = "bucket";
  List<String> clusterNodes1 = Arrays.asList("cluster1");
  List<String> clusterNodes2 = Arrays.asList("cluster2");
  CouchbaseEnvironmentConfigs configs = new CouchbaseEnvironmentConfigs();
  CouchbaseCluster cluster1 = mock(CouchbaseCluster.class);
  CouchbaseCluster cluster2 = mock(CouchbaseCluster.class);
  when(cluster1.openBucket(bucketName)).thenReturn(mock(Bucket.class));
  when(cluster2.openBucket(bucketName)).thenReturn(mock(Bucket.class));
  mockStatic(CouchbaseCluster.class);
  when(CouchbaseCluster.create(any(CouchbaseEnvironment.class), eq(clusterNodes1))).thenReturn(cluster1);
  when(CouchbaseCluster.create(any(CouchbaseEnvironment.class), eq(clusterNodes2))).thenReturn(cluster2);
  CouchbaseBucketRegistry registry = new CouchbaseBucketRegistry();
  Bucket bucketInCluster1 = registry.getBucket(bucketName, clusterNodes1, configs);
  Bucket bucketInCluster2 = registry.getBucket(bucketName, clusterNodes2, configs);
  assertNotEquals(bucketInCluster1, bucketInCluster2);
}
 
Example #8
Source File: TestCouchbaseBucketRegistry.java    From samza with Apache License 2.0 6 votes vote down vote up
/**
 * This unit test uses CouchbaseBucketRegistry to register two mocked buckets. It tests:
 * 1. Calling registry.getBucket with same bucketName and clusterNodes should return same Bucket instance
 * 2. Calling registry.getBucket with different bucketNames should return different Bucket instances
 */
@Test
public void testOpenBuckets() {
  String bucketName1 = "bucket1";
  String bucketName2 = "bucket2";
  List<String> clusterNodes = Arrays.asList("cluster");
  CouchbaseEnvironmentConfigs configs = new CouchbaseEnvironmentConfigs();
  CouchbaseCluster cluster = mock(CouchbaseCluster.class);
  when(cluster.openBucket(bucketName1)).thenReturn(mock(Bucket.class));
  when(cluster.openBucket(bucketName2)).thenReturn(mock(Bucket.class));
  mockStatic(CouchbaseCluster.class);
  when(CouchbaseCluster.create(any(CouchbaseEnvironment.class), anyListOf(String.class))).thenReturn(cluster);
  CouchbaseBucketRegistry registry = new CouchbaseBucketRegistry();
  Bucket bucket1 = registry.getBucket(bucketName1, clusterNodes, configs);
  Bucket bucket1Copy = registry.getBucket(bucketName1, clusterNodes, configs);
  Bucket bucket2 = registry.getBucket(bucketName2, clusterNodes, configs);
  assertEquals(bucket1, bucket1Copy);
  assertNotEquals(bucket1, bucket2);
}
 
Example #9
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 #10
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 #11
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 #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: 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 #14
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 #15
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 #16
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 #17
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 #18
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 #19
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 #20
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 #21
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 #22
Source File: CouchbasePipeline.java    From NetDiscovery with Apache License 2.0 5 votes vote down vote up
public CouchbasePipeline(CouchbaseCluster cluster, Bucket bucket, String documentId, long pipelineDelay){

        super(pipelineDelay);
        this.cluster = cluster;
        this.bucket = bucket;
        this.documentId = documentId;
    }
 
Example #23
Source File: TestCouchbaseBucketRegistry.java    From samza with Apache License 2.0 5 votes vote down vote up
/**
 * This unit test simulates closing two buckets within one cluster. The cluster should only be disconnected when all
 * buckets has been closed.
 */
@Test
public void testCloseTwoBucketsInSameCluster() {
  String bucketName1 = "bucket1";
  String bucketName2 = "bucket2";
  List<String> clusterNodes = Arrays.asList("cluster");
  CouchbaseEnvironmentConfigs configs = new CouchbaseEnvironmentConfigs();
  CouchbaseCluster cluster = mock(CouchbaseCluster.class);
  Bucket bucket1 = mock(Bucket.class);
  Bucket bucket2 = mock(Bucket.class);
  when(bucket1.close()).thenReturn(true).thenReturn(false);
  when(bucket2.close()).thenReturn(true).thenReturn(false);
  when(cluster.openBucket(bucketName1)).thenReturn(bucket1);
  when(cluster.openBucket(bucketName2)).thenReturn(bucket2);
  when(cluster.disconnect()).thenReturn(true).thenReturn(false);
  mockStatic(CouchbaseCluster.class);
  when(CouchbaseCluster.create(any(CouchbaseEnvironment.class), eq(clusterNodes))).thenReturn(cluster);
  CouchbaseBucketRegistry registry = new CouchbaseBucketRegistry();
  registry.getBucket(bucketName1, clusterNodes, configs);
  registry.getBucket(bucketName2, clusterNodes, configs);
  assertTrue(registry.closeBucket(bucketName1, clusterNodes));
  assertTrue(registry.closeBucket(bucketName2, clusterNodes));
  // Cluster should have been disconnected. Should return false.
  assertFalse(cluster.disconnect());
  // Buckets should have been closed. Should return false.
  assertFalse(cluster.disconnect());
}
 
Example #24
Source File: CouchbasePipeline.java    From NetDiscovery with Apache License 2.0 5 votes vote down vote up
public CouchbasePipeline(CouchbaseCluster cluster, String bucketName, String documentId, long pipelineDelay){

        super(pipelineDelay);
        this.cluster = cluster;
        this.bucket = cluster.openBucket(bucketName);
        this.documentId = documentId;
    }
 
Example #25
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 #26
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 #27
Source File: WorkloadGenerator.java    From java-dcp-client with Apache License 2.0 5 votes vote down vote up
public static void main(String... args) throws Exception {
  CouchbaseCluster cluster = CouchbaseCluster.create("127.0.0.1").authenticate("Administrator", "password");
  Bucket bucket = cluster.openBucket("default");

  while (true) {
    for (int i = 0; i < 1024; i++) {
      bucket.upsert(JsonDocument.create("doc:" + i, JsonObject.create().put("uuid", UUID.randomUUID().toString())));
      Thread.sleep(1000);
    }
  }
}
 
Example #28
Source File: CouchbaseConnectionTest.java    From components with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
    PowerMockito.mockStatic(CouchbaseCluster.class);
    cluster = Mockito.mock(CouchbaseCluster.class);
    Mockito.when(CouchbaseCluster.create(Mockito.any(CouchbaseEnvironment.class), Mockito.eq("testNode"))).thenReturn(cluster);
    connection = new CouchbaseConnection("testNode", "testBucket", "defaultPassword");
    bucket = Mockito.mock(Bucket.class);
    Mockito.when(cluster.openBucket(Mockito.anyString(), Mockito.anyString())).thenReturn(bucket);
}
 
Example #29
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 #30
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");
}