com.couchbase.client.java.env.DefaultCouchbaseEnvironment Java Examples

The following examples show how to use com.couchbase.client.java.env.DefaultCouchbaseEnvironment. 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: CouchbaseWriterTest.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
@BeforeSuite
public void startServers() {
  _couchbaseTestServer = new CouchbaseTestServer(TestUtils.findFreePort());
  _couchbaseTestServer.start();
  _couchbaseEnvironment = DefaultCouchbaseEnvironment.builder().bootstrapHttpEnabled(true)
      .bootstrapHttpDirectPort(_couchbaseTestServer.getPort())
      .bootstrapCarrierDirectPort(_couchbaseTestServer.getServerPort()).bootstrapCarrierEnabled(false)
      .kvTimeout(10000).build();
}
 
Example #4
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 #5
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 #6
Source File: ReactiveCouchbaseConfiguration.java    From tutorials with MIT License 5 votes vote down vote up
@Override
public CouchbaseEnvironment couchbaseEnvironment() {
    return DefaultCouchbaseEnvironment
      .builder()
      .bootstrapHttpDirectPort(couchbaseProperties.getPort())
      .build();
}
 
Example #7
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 #8
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 #9
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 #10
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 #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: CouchbaseEnvironmentFactory.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
/**
 * Currently hands out a singleton DefaultCouchbaseEnvironment.
 * This is done because it is recommended to use a single couchbase environment instance per JVM.
 * TODO: Determine if we need to use the config to tweak certain parameters
 * @param config
 * @return
 */
public static synchronized CouchbaseEnvironment getInstance(Config config)
{
  Boolean sslEnabled = ConfigUtils.getBoolean(config, CouchbaseWriterConfigurationKeys.SSL_ENABLED, false);
  String sslKeystoreFile = ConfigUtils.getString(config, CouchbaseWriterConfigurationKeys.SSL_KEYSTORE_FILE, "");
  String sslKeystorePassword = ConfigUtils.getString(config, CouchbaseWriterConfigurationKeys.SSL_KEYSTORE_PASSWORD, "");
  String sslTruststoreFile = ConfigUtils.getString(config, CouchbaseWriterConfigurationKeys.SSL_TRUSTSTORE_FILE, "");
  String sslTruststorePassword = ConfigUtils.getString(config, CouchbaseWriterConfigurationKeys.SSL_TRUSTSTORE_PASSWORD, "");
  Boolean certAuthEnabled = ConfigUtils.getBoolean(config, CouchbaseWriterConfigurationKeys.CERT_AUTH_ENABLED, false);
  Boolean dnsSrvEnabled = ConfigUtils.getBoolean(config, CouchbaseWriterConfigurationKeys.DNS_SRV_ENABLED, false);
  Integer socketConnectTimeout = ConfigUtils.getInt(config, CouchbaseWriterConfigurationKeys.SOCKET_CONNECT_TIMEOUT,
      DefaultCouchbaseEnvironment.SOCKET_CONNECT_TIMEOUT);

  DefaultCouchbaseEnvironment.Builder builder = DefaultCouchbaseEnvironment.builder()
      .sslEnabled(sslEnabled)
      .sslKeystoreFile(sslKeystoreFile)
      .sslKeystorePassword(sslKeystorePassword)
      .sslTruststoreFile(sslTruststoreFile)
      .sslTruststorePassword(sslTruststorePassword)
      .certAuthEnabled(certAuthEnabled)
      .dnsSrvEnabled(dnsSrvEnabled)
      .socketConnectTimeout(socketConnectTimeout);

  if (couchbaseEnvironment == null)
  {
    couchbaseEnvironment = builder.build();
  }
  return couchbaseEnvironment;
}
 
Example #13
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 #14
Source File: CouchbaseConfig.java    From spring-reactive-sample with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected CouchbaseEnvironment getEnvironment() {
    return DefaultCouchbaseEnvironment.builder()
        .connectTimeout(10000)
        .kvTimeout(10000)
        .queryTimeout(10000)
        .viewTimeout(10000)
        .build();
}
 
Example #15
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 #16
Source File: CouchbaseConnection.java    From components with Apache License 2.0 4 votes vote down vote up
public CouchbaseConnection(String bootstrapNodes, String bucket, String password) {
    CouchbaseEnvironment environment = new DefaultCouchbaseEnvironment.Builder().connectTimeout(20000L).build();
    this.cluster = CouchbaseCluster.create(environment, bootstrapNodes);
    this.bucketName = bucket;
    this.password = password;
}
 
Example #17
Source File: TestCouchbaseTarget.java    From datacollector with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
private static CouchbaseConnector getConnector(Class responseClass) throws Exception {
  ENV = DefaultCouchbaseEnvironment.create();

  CouchbaseCore core = mock(CouchbaseCore.class);
  CouchbaseAsyncBucket asyncBucket = new CouchbaseAsyncBucket(core,
      ENV,
      BUCKET,
      USERNAME,
      PASSWORD,
      Collections.emptyList()
  );

  final CouchbaseRequest requestMock = mock(CouchbaseRequest.class);

  Subject<CouchbaseResponse, CouchbaseResponse> response = AsyncSubject.create();

  if(responseClass == SimpleSubdocResponse.class) {
    final BinarySubdocRequest subdocRequestMock = mock(BinarySubdocRequest.class);
    when(subdocRequestMock.span()).thenReturn(mock(Span.class));

    response.onNext(new SimpleSubdocResponse(ResponseStatus.SUCCESS,
        KeyValueStatus.SUCCESS.code(),
        BUCKET,
        Unpooled.EMPTY_BUFFER,
        subdocRequestMock,
        1234,
        null
    ));

    response.onCompleted();
  } else {

    Constructor con = responseClass.getConstructor(ResponseStatus.class,
        short.class,
        long.class,
        String.class,
        ByteBuf.class,
        MutationToken.class,
        CouchbaseRequest.class
    );

    response.onNext((CouchbaseResponse) con.newInstance(ResponseStatus.SUCCESS,
        KeyValueStatus.SUCCESS.code(),
        1234,
        BUCKET,
        Unpooled.EMPTY_BUFFER,
        null,
        requestMock
    ));
    response.onCompleted();
  }

  when(core.send(any(BinarySubdocRequest.class))).thenReturn(response);
  when(core.send(any())).thenReturn(response);
  when(requestMock.span()).thenReturn(mock(Span.class));

  CouchbaseConnector connector = mock(CouchbaseConnector.class);
  when(connector.getScheduler()).thenReturn(ENV.scheduler());
  when(connector.bucket()).thenReturn(asyncBucket);

  return connector;
}
 
Example #18
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 #19
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 #20
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 #21
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 #22
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");
}