Best Testcontainers-java code snippet using org.testcontainers.couchbase.CouchbaseContainer.doHttpRequest
Source:CouchbaseContainer.java
...240 /**241 * Fetches edition (enterprise or community) of started container.242 */243 private void initializeIsEnterprise() {244 @Cleanup Response response = doHttpRequest(MGMT_PORT, "/pools", "GET", null, true);245 try {246 isEnterprise = MAPPER.readTree(response.body().string()).get("isEnterprise").asBoolean();247 } catch (IOException e) {248 throw new IllegalStateException("Couchbase /pools did not return valid JSON");249 }250 if (!isEnterprise && enabledServices.contains(CouchbaseService.ANALYTICS)) {251 throw new IllegalStateException("The Analytics Service is only supported with the Enterprise version");252 }253 }254 /**255 * Rebinds/renames the internal hostname.256 * <p>257 * To make sure the internal hostname is different from the external (alternate) address and the SDK can pick it258 * up automatically, we bind the internal hostname to the internal IP address.259 */260 private void renameNode() {261 logger().debug("Renaming Couchbase Node from localhost to {}", getHost());262 @Cleanup Response response = doHttpRequest(MGMT_PORT, "/node/controller/rename", "POST", new FormBody.Builder()263 .add("hostname", getInternalIpAddress())264 .build(), false265 );266 checkSuccessfulResponse(response, "Could not rename couchbase node");267 }268 /**269 * Initializes services based on the configured enabled services.270 */271 private void initializeServices() {272 logger().debug("Initializing couchbase services on host: {}", enabledServices);273 final String services = enabledServices274 .stream()275 .map(CouchbaseService::getIdentifier)276 .collect(Collectors.joining(","));277 @Cleanup Response response = doHttpRequest(MGMT_PORT, "/node/controller/setupServices", "POST", new FormBody.Builder()278 .add("services", services)279 .build(), false280 );281 checkSuccessfulResponse(response, "Could not enable couchbase services");282 }283 /**284 * Configures the admin user on the couchbase node.285 * <p>286 * After this stage, all subsequent API calls need to have the basic auth header set.287 */288 private void configureAdminUser() {289 logger().debug("Configuring couchbase admin user with username: \"{}\"", username);290 @Cleanup Response response = doHttpRequest(MGMT_PORT, "/settings/web", "POST", new FormBody.Builder()291 .add("username", username)292 .add("password", password)293 .add("port", Integer.toString(MGMT_PORT))294 .build(), false);295 checkSuccessfulResponse(response, "Could not configure couchbase admin user");296 }297 /**298 * Configures the external ports for SDK access.299 * <p>300 * Since the internal ports are not accessible from outside the container, this code configures the "external"301 * hostname and services to align with the mapped ports. The SDK will pick it up and then automatically connect302 * to those ports. Note that for all services non-ssl and ssl ports are configured.303 */304 private void configureExternalPorts() {305 logger().debug("Mapping external ports to the alternate address configuration");306 final FormBody.Builder builder = new FormBody.Builder();307 builder.add("hostname", getHost());308 builder.add("mgmt", Integer.toString(getMappedPort(MGMT_PORT)));309 builder.add("mgmtSSL", Integer.toString(getMappedPort(MGMT_SSL_PORT)));310 if (enabledServices.contains(CouchbaseService.KV)) {311 builder.add("kv", Integer.toString(getMappedPort(KV_PORT)));312 builder.add("kvSSL", Integer.toString(getMappedPort(KV_SSL_PORT)));313 builder.add("capi", Integer.toString(getMappedPort(VIEW_PORT)));314 builder.add("capiSSL", Integer.toString(getMappedPort(VIEW_SSL_PORT)));315 }316 if (enabledServices.contains(CouchbaseService.QUERY)) {317 builder.add("n1ql", Integer.toString(getMappedPort(QUERY_PORT)));318 builder.add("n1qlSSL", Integer.toString(getMappedPort(QUERY_SSL_PORT)));319 }320 if (enabledServices.contains(CouchbaseService.SEARCH)) {321 builder.add("fts", Integer.toString(getMappedPort(SEARCH_PORT)));322 builder.add("ftsSSL", Integer.toString(getMappedPort(SEARCH_SSL_PORT)));323 }324 if (enabledServices.contains(CouchbaseService.ANALYTICS)) {325 builder.add("cbas", Integer.toString(getMappedPort(ANALYTICS_PORT)));326 builder.add("cbasSSL", Integer.toString(getMappedPort(ANALYTICS_SSL_PORT)));327 }328 @Cleanup Response response = doHttpRequest(329 MGMT_PORT,330 "/node/controller/setupAlternateAddresses/external",331 "PUT",332 builder.build(),333 true334 );335 checkSuccessfulResponse(response, "Could not configure external ports");336 }337 /**338 * Configures the indexer service so that indexes can be created later on the bucket.339 */340 private void configureIndexer() {341 logger().debug("Configuring the indexer service");342 @Cleanup Response response = doHttpRequest(MGMT_PORT, "/settings/indexes", "POST", new FormBody.Builder()343 .add("storageMode", isEnterprise ? "memory_optimized" : "forestdb")344 .build(), true345 );346 checkSuccessfulResponse(response, "Could not configure the indexing service");347 }348 /**349 * Based on the user-configured bucket definitions, creating buckets and corresponding indexes if needed.350 */351 private void createBuckets() {352 logger().debug("Creating {} buckets (and corresponding indexes).", buckets.size());353 for (BucketDefinition bucket : buckets) {354 logger().debug("Creating bucket \"{}\"", bucket.getName());355 @Cleanup Response response = doHttpRequest(MGMT_PORT, "/pools/default/buckets", "POST", new FormBody.Builder()356 .add("name", bucket.getName())357 .add("ramQuotaMB", Integer.toString(bucket.getQuota()))358 .add("flushEnabled", bucket.hasFlushEnabled() ? "1" : "0")359 .build(), true);360 checkSuccessfulResponse(response, "Could not create bucket " + bucket.getName());361 timePhase("createBucket:" + bucket.getName() + ":waitForAllServicesEnabled", () ->362 new HttpWaitStrategy()363 .forPath("/pools/default/b/" + bucket.getName())364 .forPort(MGMT_PORT)365 .withBasicCredentials(username, password)366 .forStatusCode(200)367 .forResponsePredicate(new AllServicesEnabledPredicate())368 .waitUntilReady(this)369 );370 if (enabledServices.contains(CouchbaseService.QUERY)) {371 // If the query service is enabled, make sure that we only proceed if the query engine also372 // knows about the bucket in its metadata configuration.373 timePhase(374 "createBucket:" + bucket.getName() + ":queryKeyspacePresent",375 () -> Unreliables.retryUntilTrue(1, TimeUnit.MINUTES, () -> {376 @Cleanup Response queryResponse = doHttpRequest(QUERY_PORT, "/query/service", "POST", new FormBody.Builder()377 .add("statement", "SELECT COUNT(*) > 0 as present FROM system:keyspaces WHERE name = \"" + bucket.getName() + "\"")378 .build(), true);379 String body = queryResponse.body() != null ? queryResponse.body().string() : null;380 checkSuccessfulResponse(queryResponse, "Could not poll query service state for bucket: " + bucket.getName());381 return Optional.of(MAPPER.readTree(body))382 .map(n -> n.at("/results/0/present"))383 .map(JsonNode::asBoolean)384 .orElse(false);385 }));386 }387 if (bucket.hasPrimaryIndex()) {388 if (enabledServices.contains(CouchbaseService.QUERY)) {389 @Cleanup Response queryResponse = doHttpRequest(QUERY_PORT, "/query/service", "POST", new FormBody.Builder()390 .add("statement", "CREATE PRIMARY INDEX on `" + bucket.getName() + "`")391 .build(), true);392 try {393 checkSuccessfulResponse(queryResponse, "Could not create primary index for bucket " + bucket.getName());394 } catch (IllegalStateException ex) {395 // potentially ignore the error, the index will be eventually built.396 if (!ex.getMessage().contains("Index creation will be retried in background")) {397 throw ex;398 }399 }400 timePhase(401 "createBucket:" + bucket.getName() + ":primaryIndexOnline",402 () -> Unreliables.retryUntilTrue(1, TimeUnit.MINUTES, () -> {403 @Cleanup Response stateResponse = doHttpRequest(QUERY_PORT, "/query/service", "POST", new FormBody.Builder()404 .add("statement", "SELECT count(*) > 0 AS online FROM system:indexes where keyspace_id = \"" + bucket.getName() + "\" and is_primary = true and state = \"online\"")405 .build(), true);406 String body = stateResponse.body() != null ? stateResponse.body().string() : null;407 checkSuccessfulResponse(stateResponse, "Could not poll primary index state for bucket: " + bucket.getName());408 return Optional.of(MAPPER.readTree(body))409 .map(n -> n.at("/results/0/online"))410 .map(JsonNode::asBoolean)411 .orElse(false);412 }));413 } else {414 logger().info("Primary index creation for bucket {} ignored, since QUERY service is not present.", bucket.getName());415 }416 }417 }418 }419 /**420 * Helper method to extract the internal IP address based on the network configuration.421 */422 private String getInternalIpAddress() {423 return getContainerInfo().getNetworkSettings().getNetworks().values().stream()424 .findFirst()425 .map(ContainerNetwork::getIpAddress)426 .orElseThrow(() -> new IllegalStateException("No network available to extract the internal IP from!"));427 }428 /**429 * Helper method to check if the response is successful and release the body if needed.430 *431 * @param response the response to check.432 * @param message the message that should be part of the exception of not successful.433 */434 private void checkSuccessfulResponse(final Response response, final String message) {435 if (!response.isSuccessful()) {436 String body = null;437 if (response.body() != null) {438 try {439 body = response.body().string();440 } catch (IOException e) {441 logger().debug("Unable to read body of response: {}", response, e);442 }443 }444 throw new IllegalStateException(message + ": " + response + ", body=" + (body == null ? "<null>" : body));445 }446 }447 /**448 * Checks if already running and if so raises an exception to prevent too-late setters.449 */450 private void checkNotRunning() {451 if (isRunning()) {452 throw new IllegalStateException("Setter can only be called before the container is running");453 }454 }455 /**456 * Helper method to perform a request against a couchbase server HTTP endpoint.457 *458 * @param port the (unmapped) original port that should be used.459 * @param path the relative http path.460 * @param method the http method to use.461 * @param body if present, will be part of the payload.462 * @param auth if authentication with the admin user and password should be used.463 * @return the response of the request.464 */465 private Response doHttpRequest(final int port, final String path, final String method, final RequestBody body,466 final boolean auth) {467 try {468 Request.Builder requestBuilder = new Request.Builder()469 .url("http://" + getHost() + ":" + getMappedPort(port) + path);470 if (auth) {471 requestBuilder = requestBuilder.header("Authorization", Credentials.basic(username, password));472 }473 if (body == null) {474 requestBuilder = requestBuilder.get();475 } else {476 requestBuilder = requestBuilder.method(method, body);477 }478 return HTTP_CLIENT.newCall(requestBuilder.build()).execute();479 } catch (Exception ex) {...
doHttpRequest
Using AI Code Generation
1import org.testcontainers.couchbase.CouchbaseContainer2import org.testcontainers.couchbase.BucketDefinition3import org.testcontainers.couchbase.BucketType4CouchbaseContainer couchbase = new CouchbaseContainer("couchbase:5.5.0")5 .withBucket(new BucketDefinition("test")6 .withType(BucketType.COUCHBASE)7 .withQuota(100)8 .withIndexReplicas(false))9 .withClusterAdmin("Administrator", "password")10 .withNewBucket(BucketDefinition.builder()11 .withName("test2")12 .withType(BucketType.MEMCACHED)13 .withQuota(100)14 .withIndexReplicas(false)15 .build())16couchbase.start()17def response = couchbase.doHttpRequest("/pools/default/buckets/test", "GET", null, null)18println response.getStatusLine().getStatusCode()19println response.getEntity().getContent()20couchbase.stop()
doHttpRequest
Using AI Code Generation
1CouchbaseContainer couchbase = new CouchbaseContainer()2couchbase.start()3int port = couchbase.getMappedPort(8091)4doHttpRequest(port, "GET", "/pools/default")5couchbase.stop()6CouchbaseContainer couchbase = new CouchbaseContainer()7couchbase.start()8int port = couchbase.getMappedPort(8091)9doHttpRequest(port, "GET", "/pools/default")10couchbase.stop()11CouchbaseContainer couchbase = new CouchbaseContainer()12couchbase.start()13int port = couchbase.getMappedPort(8091)14doHttpRequest(port, "GET", "/pools/default")15couchbase.stop()16CouchbaseContainer couchbase = new CouchbaseContainer()17couchbase.start()18int port = couchbase.getMappedPort(8091)19doHttpRequest(port, "GET", "/pools/default")20couchbase.stop()21CouchbaseContainer couchbase = new CouchbaseContainer()22couchbase.start()
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!