How to use caCertAsBytes method of org.testcontainers.elasticsearch.ElasticsearchContainer class

Best Testcontainers-java code snippet using org.testcontainers.elasticsearch.ElasticsearchContainer.caCertAsBytes

Source:ElasticsearchContainerTest.java Github

copy

Full Screen

...397 credentialsProvider.setCredentials(398 AuthScope.ANY,399 new UsernamePasswordCredentials(ELASTICSEARCH_USERNAME, ELASTICSEARCH_PASSWORD)400 );401 String protocol = container.caCertAsBytes().isPresent() ? "https://" : "http://";402 client =403 RestClient404 .builder(HttpHost.create(protocol + container.getHttpHostAddress()))405 .setHttpClientConfigCallback(httpClientBuilder -> {406 if (container.caCertAsBytes().isPresent()) {407 httpClientBuilder.setSSLContext(container.createSslContextFromCa());408 }409 return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);410 })411 .build();412 }413 return client;414 }415 private RestClient getAnonymousClient(ElasticsearchContainer container) {416 if (anonymousClient == null) {417 anonymousClient = RestClient.builder(HttpHost.create(container.getHttpHostAddress())).build();418 }419 return anonymousClient;420 }...

Full Screen

Full Screen

Source:ElasticsearchContainer.java Github

copy

Full Screen

...53 @Deprecated54 protected static final String DEFAULT_TAG = "7.9.2";55 private final boolean isOss;56 private final boolean isAtLeastMajorVersion8;57 private Optional<byte[]> caCertAsBytes = Optional.empty();58 private String certPath = "/usr/share/elasticsearch/config/certs/http_ca.crt";59 /**60 * @deprecated use {@link ElasticsearchContainer(DockerImageName)} instead61 */62 @Deprecated63 public ElasticsearchContainer() {64 this(DEFAULT_IMAGE_NAME.withTag(DEFAULT_TAG));65 }66 /**67 * Create an Elasticsearch Container by passing the full docker image name68 * @param dockerImageName Full docker image name as a {@link String}, like: docker.elastic.co/elasticsearch/elasticsearch:7.9.269 */70 public ElasticsearchContainer(String dockerImageName) {71 this(DockerImageName.parse(dockerImageName));72 }73 /**74 * Create an Elasticsearch Container by passing the full docker image name75 * @param dockerImageName Full docker image name as a {@link DockerImageName}, like: DockerImageName.parse("docker.elastic.co/elasticsearch/elasticsearch:7.9.2")76 */77 public ElasticsearchContainer(final DockerImageName dockerImageName) {78 super(dockerImageName);79 dockerImageName.assertCompatibleWith(DEFAULT_IMAGE_NAME, DEFAULT_OSS_IMAGE_NAME);80 this.isOss = dockerImageName.isCompatibleWith(DEFAULT_OSS_IMAGE_NAME);81 logger().info("Starting an elasticsearch container using [{}]", dockerImageName);82 withNetworkAliases("elasticsearch-" + Base58.randomString(6));83 withEnv("discovery.type", "single-node");84 // Sets default memory of elasticsearch instance to 2GB85 // Spaces are deliberate to allow user to define additional jvm options as elasticsearch resolves option files lexicographically86 withClasspathResourceMapping(87 "elasticsearch-default-memory-vm.options",88 "/usr/share/elasticsearch/config/jvm.options.d/ elasticsearch-default-memory-vm.options",89 BindMode.READ_ONLY90 );91 addExposedPorts(ELASTICSEARCH_DEFAULT_PORT, ELASTICSEARCH_DEFAULT_TCP_PORT);92 this.isAtLeastMajorVersion8 =93 new ComparableVersion(dockerImageName.getVersionPart()).isGreaterThanOrEqualTo("8.0.0");94 // regex that95 // matches 8.3 JSON logging with started message and some follow up content within the message field96 // matches 8.0 JSON logging with no whitespace between message field and content97 // matches 7.x JSON logging with whitespace between message field and content98 // matches 6.x text logging with node name in brackets and just a 'started' message till the end of the line99 String regex = ".*(\"message\":\\s?\"started[\\s?|\"].*|] started\n$)";100 setWaitStrategy(new LogMessageWaitStrategy().withRegEx(regex));101 if (isAtLeastMajorVersion8) {102 withPassword(ELASTICSEARCH_DEFAULT_PASSWORD);103 }104 }105 @Override106 protected void containerIsStarted(InspectContainerResponse containerInfo) {107 if (isAtLeastMajorVersion8 && StringUtils.isNotEmpty(certPath)) {108 try {109 byte[] bytes = copyFileFromContainer(certPath, IOUtils::toByteArray);110 if (bytes.length > 0) {111 this.caCertAsBytes = Optional.of(bytes);112 }113 } catch (NotFoundException e) {114 // just emit an error message, but do not throw an exception115 // this might be ok, if the docker image is accidentally looking like version 8 or latest116 // can happen if Elasticsearch is repackaged, i.e. with custom plugins117 log.warn("CA cert under " + certPath + " not found.");118 }119 }120 }121 /**122 * If this is running above Elasticsearch 8, this will return the probably self-signed CA cert that has been extracted123 *124 * @return byte array optional containing the CA cert extracted from the docker container125 */126 public Optional<byte[]> caCertAsBytes() {127 return caCertAsBytes;128 }129 /**130 * A SSL context based on the self signed CA, so that using this SSL Context allows to connect to the Elasticsearch service131 * @return a customized SSL Context132 */133 public SSLContext createSslContextFromCa() {134 try {135 CertificateFactory factory = CertificateFactory.getInstance("X.509");136 Certificate trustedCa = factory.generateCertificate(new ByteArrayInputStream(caCertAsBytes.get()));137 KeyStore trustStore = KeyStore.getInstance("pkcs12");138 trustStore.load(null, null);139 trustStore.setCertificateEntry("ca", trustedCa);140 final SSLContext sslContext = SSLContext.getInstance("TLSv1.3");141 TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());142 tmfactory.init(trustStore);143 sslContext.init(null, tmfactory.getTrustManagers(), null);144 return sslContext;145 } catch (Exception e) {146 throw new RuntimeException(e);147 }148 }149 /**150 * Define the Elasticsearch password to set. It enables security behind the scene for major version below 8.0.0....

Full Screen

Full Screen

Source:TransportUtilsTest.java Github

copy

Full Screen

...45 );46 }47 @Test48 public void testCaCertificate() throws Exception {49 byte[] cert = ElasticsearchTestServer.global().container().caCertAsBytes().get();50 checkConnection(51 TransportUtils.sslContextFromHttpCaCrt(new ByteArrayInputStream(cert))52 );53 }54 @Test void testCaFingerprint() throws Exception {55 byte[] pemCert = ElasticsearchTestServer.global().container().caCertAsBytes().get();56 CertificateFactory cf = CertificateFactory.getInstance("X.509");57 Certificate x509cert = cf.generateCertificate(new ByteArrayInputStream(pemCert));58 // Compute SHA-256 fingerprint, which is what ES outputs at start time59 String fingerprint = fingerprint(x509cert.getEncoded(), "SHA-256");60 checkConnection(61 TransportUtils.sslContextFromCaFingerprint(fingerprint)62 );63 }64 @Test void testInvalidFingerprint() throws Exception {65 // Build a dummy SHA-256 signature66 String fingerprint = fingerprint("foobar".getBytes(StandardCharsets.UTF_8), "SHA-256");67 assertThrows(68 SSLHandshakeException.class,69 () -> checkConnection(...

Full Screen

Full Screen

caCertAsBytes

Using AI Code Generation

copy

Full Screen

1import org.testcontainers.elasticsearch.ElasticsearchContainer;2public class 1 {3 public static void main(String[] args) {4 ElasticsearchContainer container = new ElasticsearchContainer();5 container.start();6 byte[] caCertAsBytes = container.caCertAsBytes();7 container.stop();8 }9}10Exception in thread "main" java.lang.NoSuchMethodError: org.testcontainers.elasticsearch.ElasticsearchContainer.caCertAsBytes()[B11 at 1.main(1.java:6)12ElasticsearchContainer container = new ElasticsearchContainer();13container.start();14byte[] caCertAsBytes = container.caCertAsBytes();15container.stop();16Exception in thread "main" java.lang.NoSuchMethodError: org.testcontainers.elasticsearch.ElasticsearchContainer.caCertAsBytes()[B17 at 1.main(1.java:6)18ElasticsearchContainer container = new ElasticsearchContainer();19container.start();20byte[] caCertAsBytes = container.caCertAsBytes();21container.stop();22Exception in thread "main" java.lang.NoSuchMethodError: org.testcontainers.elasticsearch.ElasticsearchContainer.caCertAsBytes()[B23 at 1.main(1.java:6)24ElasticsearchContainer container = new ElasticsearchContainer();25container.start();26byte[] caCertAsBytes = container.caCertAsBytes();27container.stop();28Exception in thread "main" java.lang.NoSuchMethodError: org.testcontainers.elasticsearch.ElasticsearchContainer.caCertAsBytes()[B29 at 1.main(1.java:6)30ElasticsearchContainer container = new ElasticsearchContainer();31container.start();32byte[] caCertAsBytes = container.caCertAsBytes();33container.stop();

Full Screen

Full Screen

caCertAsBytes

Using AI Code Generation

copy

Full Screen

1package org.testcontainers.elasticsearch;2import java.nio.file.Files;3import java.nio.file.Path;4import java.nio.file.Paths;5import java.security.cert.CertificateException;6import java.security.cert.X509Certificate;7import java.util.Base64;8import javax.net.ssl.SSLContext;9import javax.net.ssl.TrustManager;10import javax.net.ssl.X509TrustManager;11import org.apache.http.HttpHost;12import org.elasticsearch.client.RestClient;13import org.elasticsearch.client.RestHighLevelClient;14import org.junit.Test;15public class TestContainerTest {16 public void test() throws Exception {17 final Path tempDirectory = Files.createTempDirectory("es");18 final ElasticsearchContainer elasticsearchContainer = new ElasticsearchContainer("docker.elastic.co/elasticsearch/elasticsearch:7.4.0")19 .withEnv("discovery.type", "single-node")20 .withEnv("xpack.security.enabled", "false")21 .withEnv("ES_JAVA_OPTS", "-Xms512m -Xmx512m")22 .withEnv("cluster.name", "test")23 .withEnv("http.port", "9200")24 .withEnv("transport.tcp.port", "9300")25 .withEnv("ES_PATH_CONF", tempDirectory.toString())26 .withEnv("path.data", tempDirectory.toString())27 .withEnv("path.logs", tempDirectory.toString())28 .withEnv("path.repo", tempDirectory.toString())29 .withEnv("path.home", tempDirectory.toString())30 .withEnv("path.conf", tempDirectory.toString())31 .withEnv("network.host", "

Full Screen

Full Screen

caCertAsBytes

Using AI Code Generation

copy

Full Screen

1package org.testcontainers.elasticsearch;2import org.testcontainers.containers.GenericContainer;3import java.util.concurrent.TimeUnit;4public class ElasticsearchContainer extends GenericContainer<ElasticsearchContainer> {5 private static final String ELASTICSEARCH_DEFAULT_IMAGE = "docker.elastic.co/elasticsearch/elasticsearch";6 private static final String ELASTICSEARCH_DEFAULT_TAG = "7.4.0";7 public ElasticsearchContainer() {8 this(ELASTICSEARCH_DEFAULT_IMAGE + ":" + ELASTICSEARCH_DEFAULT_TAG);9 }10 public ElasticsearchContainer(String dockerImageName) {11 super(dockerImageName);12 }13 protected void configure() {14 addExposedPort(9200);15 addExposedPort(9300);16 setWaitStrategy(new ElasticsearchWaitStrategy());17 }18 public static class ElasticsearchWaitStrategy extends AbstractWaitStrategy {19 protected void waitUntilReady() {

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Testcontainers-java automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful