How to use effectiveRegistryName method of org.testcontainers.utility.RegistryAuthLocator class

Best Testcontainers-java code snippet using org.testcontainers.utility.RegistryAuthLocator.effectiveRegistryName

Source:RegistryAuthLocator.java Github

copy

Full Screen

...81 * @param defaultAuthConfig an AuthConfig object that should be returned if there is no overriding authentication available for images that are looked up82 * @return an AuthConfig that is applicable to this specific image OR the defaultAuthConfig.83 */84 public AuthConfig lookupAuthConfig(DockerImageName dockerImageName, AuthConfig defaultAuthConfig) {85 final String registryName = effectiveRegistryName(dockerImageName);86 log.debug("Looking up auth config for image: {} at registry: {}", dockerImageName, registryName);87 final Optional<AuthConfig> cachedAuth = cache.computeIfAbsent(registryName, __ -> lookupUncachedAuthConfig(registryName, dockerImageName));88 if (cachedAuth.isPresent()) {89 log.debug("Cached auth found: [{}]", toSafeString(cachedAuth.get()));90 return cachedAuth.get();91 } else {92 log.debug("No matching Auth Configs - falling back to defaultAuthConfig [{}]", toSafeString(defaultAuthConfig));93 // otherwise, defaultAuthConfig should already contain any credentials available94 return defaultAuthConfig;95 }96 }97 private Optional<AuthConfig> lookupUncachedAuthConfig(String registryName, DockerImageName dockerImageName) {98 log.debug("RegistryAuthLocator has configFile: {} ({}) and commandPathPrefix: {}",99 configFile,100 configFile.exists() ? "exists" : "does not exist",101 commandPathPrefix);102 try {103 final JsonNode config = OBJECT_MAPPER.readTree(configFile);104 log.debug("registryName [{}] for dockerImageName [{}]", registryName, dockerImageName);105 // use helper preferentially (per https://docs.docker.com/engine/reference/commandline/cli/)106 final AuthConfig helperAuthConfig = authConfigUsingHelper(config, registryName);107 if (helperAuthConfig != null) {108 log.debug("found helper auth config [{}]", toSafeString(helperAuthConfig));109 return Optional.of(helperAuthConfig);110 }111 // no credsHelper to use, using credsStore:112 final AuthConfig storeAuthConfig = authConfigUsingStore(config, registryName);113 if (storeAuthConfig != null) {114 log.debug("found creds store auth config [{}]", toSafeString(storeAuthConfig));115 return Optional.of(storeAuthConfig);116 }117 // fall back to base64 encoded auth hardcoded in config file118 final AuthConfig existingAuthConfig = findExistingAuthConfig(config, registryName);119 if (existingAuthConfig != null) {120 log.debug("found existing auth config [{}]", toSafeString(existingAuthConfig));121 return Optional.of(existingAuthConfig);122 }123 } catch (Exception e) {124 log.warn("Failure when attempting to lookup auth config (dockerImageName: {}, configFile: {}. Falling back to docker-java default behaviour. Exception message: {}",125 dockerImageName,126 configFile,127 e.getMessage());128 }129 return Optional.empty();130 }131 private AuthConfig findExistingAuthConfig(final JsonNode config, final String reposName) throws Exception {132 final Map.Entry<String, JsonNode> entry = findAuthNode(config, reposName);133 if (entry != null && entry.getValue() != null && entry.getValue().size() > 0) {134 final AuthConfig deserializedAuth = OBJECT_MAPPER135 .treeToValue(entry.getValue(), AuthConfig.class)136 .withRegistryAddress(entry.getKey());137 if (isBlank(deserializedAuth.getUsername()) &&138 isBlank(deserializedAuth.getPassword()) &&139 !isBlank(deserializedAuth.getAuth())) {140 final String rawAuth = new String(Base64.getDecoder().decode(deserializedAuth.getAuth()));141 final String[] splitRawAuth = rawAuth.split(":", 2);142 if (splitRawAuth.length == 2) {143 deserializedAuth.withUsername(splitRawAuth[0]);144 deserializedAuth.withPassword(splitRawAuth[1]);145 }146 }147 return deserializedAuth;148 }149 return null;150 }151 private AuthConfig authConfigUsingHelper(final JsonNode config, final String reposName) throws Exception {152 final JsonNode credHelpers = config.get("credHelpers");153 if (credHelpers != null && credHelpers.size() > 0) {154 final JsonNode helperNode = credHelpers.get(reposName);155 if (helperNode != null && helperNode.isTextual()) {156 final String helper = helperNode.asText();157 return runCredentialProvider(reposName, helper);158 }159 }160 return null;161 }162 private AuthConfig authConfigUsingStore(final JsonNode config, final String reposName) throws Exception {163 final JsonNode credsStoreNode = config.get("credsStore");164 if (credsStoreNode != null && !credsStoreNode.isMissingNode() && credsStoreNode.isTextual()) {165 final String credsStore = credsStoreNode.asText();166 if (isBlank(credsStore)) {167 log.warn("Docker auth config credsStore field will be ignored, because value is blank");168 return null;169 }170 return runCredentialProvider(reposName, credsStore);171 }172 return null;173 }174 private Map.Entry<String, JsonNode> findAuthNode(final JsonNode config, final String reposName) {175 final JsonNode auths = config.get("auths");176 if (auths != null && auths.size() > 0) {177 final Iterator<Map.Entry<String, JsonNode>> fields = auths.fields();178 while (fields.hasNext()) {179 final Map.Entry<String, JsonNode> entry = fields.next();180 if (entry.getKey().contains("://" + reposName) || entry.getKey().equals(reposName)) {181 return entry;182 }183 }184 }185 return null;186 }187 private AuthConfig runCredentialProvider(String hostName, String helperOrStoreName) throws Exception {188 if (isBlank(hostName)) {189 log.debug("There is no point in locating AuthConfig for blank hostName. Returning NULL to allow fallback");190 return null;191 }192 final String credentialProgramName = getCredentialProgramName(helperOrStoreName);193 final String data;194 log.debug("Executing docker credential provider: {} to locate auth config for: {}",195 credentialProgramName, hostName);196 try {197 data = runCredentialProgram(hostName, credentialProgramName);198 } catch (InvalidResultException e) {199 final String responseErrorMsg = extractCredentialProviderErrorMessage(e);200 if (!isBlank(responseErrorMsg)) {201 String credentialsNotFoundMsg = getGenericCredentialsNotFoundMsg(credentialProgramName);202 if (credentialsNotFoundMsg != null && credentialsNotFoundMsg.equals(responseErrorMsg)) {203 log.info("Credential helper/store ({}) does not have credentials for {}",204 credentialProgramName,205 hostName);206 return null;207 }208 log.debug("Failure running docker credential helper/store ({}) with output '{}'",209 credentialProgramName, responseErrorMsg);210 } else {211 log.debug("Failure running docker credential helper/store ({})", credentialProgramName);212 }213 throw e;214 } catch (Exception e) {215 log.debug("Failure running docker credential helper/store ({})", credentialProgramName);216 throw e;217 }218 final JsonNode helperResponse = OBJECT_MAPPER.readTree(data);219 log.debug("Credential helper/store provided auth config for: {}", hostName);220 final String username = helperResponse.at("/Username").asText();221 final String password = helperResponse.at("/Secret").asText();222 if ("<token>".equals(username)) {223 return new AuthConfig().withIdentityToken(password);224 } else {225 return new AuthConfig()226 .withRegistryAddress(helperResponse.at("/ServerURL").asText())227 .withUsername(username)228 .withPassword(password);229 }230 }231 private String getCredentialProgramName(String credHelper) {232 return commandPathPrefix + "docker-credential-" + credHelper + commandExtension;233 }234 private String effectiveRegistryName(DockerImageName dockerImageName) {235 return StringUtils.defaultIfEmpty(dockerImageName.getRegistry(), DEFAULT_REGISTRY_NAME);236 }237 private String getGenericCredentialsNotFoundMsg(String credentialHelperName) {238 if (!CREDENTIALS_HELPERS_NOT_FOUND_MESSAGE_CACHE.containsKey(credentialHelperName)) {239 String credentialsNotFoundMsg = discoverCredentialsHelperNotFoundMessage(credentialHelperName);240 if (!isBlank(credentialsNotFoundMsg)) {241 CREDENTIALS_HELPERS_NOT_FOUND_MESSAGE_CACHE.put(credentialHelperName, credentialsNotFoundMsg);242 }243 }244 return CREDENTIALS_HELPERS_NOT_FOUND_MESSAGE_CACHE.get(credentialHelperName);245 }246 private String discoverCredentialsHelperNotFoundMessage(String credentialHelperName) {247 // will do fake call to given credential helper to find out with which message248 // it response when there are no credentials for given hostName...

Full Screen

Full Screen

effectiveRegistryName

Using AI Code Generation

copy

Full Screen

1 String registryName = "registry.testcontainers.org";2 String image = "alpine:3.8";3 String effectiveRegistryName = RegistryAuthLocator.effectiveRegistryName(image, registryName);4 System.out.println("Effective registry name: " + effectiveRegistryName);5 ImageName imageName = new ImageName(image);6 System.out.println("Image name: " + imageName.getUnversionedPart());7 System.out.println("Image version: " + imageName.getVersionPart());8 DockerImageName dockerImageName = DockerImageName.parse(image);9 System.out.println("Image name: " + dockerImageName.getUnversionedPart());10 System.out.println("Image version: " + dockerImageName.getVersionPart());11}

Full Screen

Full Screen

effectiveRegistryName

Using AI Code Generation

copy

Full Screen

1import org.testcontainers.containers.GenericContainer;2import java.io.IOException;3public class TestContainer {4 public static void main(String[] args) throws IOException {5 GenericContainer container = new GenericContainer("registry.hub.docker.com/library/hello-world:latest");6 container.start();7 System.out.println("Container started");8 }9}10 at org.testcontainers.containers.GenericContainer.getDockerClient(GenericContainer.java:1188)11 at org.testcontainers.containers.GenericContainer.logger(GenericContainer.java:526)12 at org.testcontainers.containers.GenericContainer.doStart(GenericContainer.java:312)13 at org.testcontainers.containers.GenericContainer.start(GenericContainer.java:302)14 at TestContainer.main(TestContainer.java:12)15 at org.testcontainers.containers.GenericContainer.getDockerClient(GenericContainer.java:1185)16 at org.testcontainers.utility.RegistryAuthLocator.getAuthConfig(RegistryAuthLocator.java:46)17 at org.testcontainers.DockerClientFactory.build(DockerClientFactory.java:162)18 at org.testcontainers.DockerClientFactory.client(DockerClientFactory.java:196)19 at org.testcontainers.DockerClientFactory.client(DockerClientFactory.java:191)20 at org.testcontainers.containers.GenericContainer.getDockerClient(GenericContainer.java:1183)

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.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful