Skip to content

Commit

Permalink
make serviceregion configurable in examples
Browse files Browse the repository at this point in the history
  • Loading branch information
jenschude committed Feb 21, 2025
1 parent c5ef6ce commit 4c387e5
Show file tree
Hide file tree
Showing 15 changed files with 118 additions and 28 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import java.util.Optional;

public class GettingStarted {

@Test
Expand All @@ -16,7 +18,7 @@ public void project() {
ClientCredentials.of().withClientId(System.getenv("CTP_CLIENT_ID"))
.withClientSecret(System.getenv("CTP_CLIENT_SECRET"))
.build(),
ServiceRegion.GCP_EUROPE_WEST1).build(System.getenv("CTP_PROJECT_KEY"));
ServiceRegion.valueOf(Optional.ofNullable(System.getenv("CTP_SERVICE_REGION")).orElse("GCP_EUROPE_WEST1"))).build(System.getenv("CTP_PROJECT_KEY"));

Project response = apiRoot
.get()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import java.util.Optional;

public class GettingStarted {

@Test
Expand All @@ -16,7 +18,7 @@ public void project() {
ClientCredentials.of().withClientId(System.getenv("CTP_CLIENT_ID"))
.withClientSecret(System.getenv("CTP_CLIENT_SECRET"))
.build(),
ServiceRegion.GCP_EUROPE_WEST1).build(System.getenv("CTP_PROJECT_KEY"));
ServiceRegion.valueOf(Optional.ofNullable(System.getenv("CTP_SERVICE_REGION")).orElse("GCP_EUROPE_WEST1"))).build(System.getenv("CTP_PROJECT_KEY"));

Project response = apiRoot
.get()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

import com.commercetools.api.client.ProjectScopedApiRoot;
import com.commercetools.api.defaultconfig.ApiRootBuilder;
import com.commercetools.api.defaultconfig.ServiceRegion;
import com.commercetools.monitoring.datadog.statsd.DatadogMiddleware;
import com.commercetools.monitoring.datadog.statsd.DatadogResponseSerializer;
import com.timgroup.statsd.NonBlockingStatsDClientBuilder;
Expand All @@ -15,6 +16,8 @@
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Optional;

@Configuration
@EnableAutoConfiguration
public class CtpClientBeanService {
Expand All @@ -28,18 +31,26 @@ public class CtpClientBeanService {
@Value(value = "${ctp.project.key}")
private String projectKey;

@Value(value = "${ctp.service.region:#{null}}")
private String serviceRegion;

private ClientCredentials credentials() {
return ClientCredentials.of().withClientId(clientId).withClientSecret(clientSecret).build();
}

@Bean
public ServiceRegion serviceRegion() {
return ServiceRegion.valueOf(Optional.ofNullable(this.serviceRegion).orElse("GCP_EUROPE_WEST1"));
}

@Bean
public ProjectScopedApiRoot apiRoot() {
StatsDClient statsd = new NonBlockingStatsDClientBuilder()
.hostname("localhost")
.build();

ApiRootBuilder builder = ApiRootBuilder.of()
.defaultClient(credentials())
.defaultClient(credentials(), serviceRegion())
.withSerializer(new DatadogResponseSerializer(ResponseSerializer.of(), statsd))
.withTelemetryMiddleware(new DatadogMiddleware(statsd));
return builder.build(projectKey);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,8 @@ public static class CtpReactiveAuthenticationManagerResolver
implements ReactiveAuthenticationManagerResolver<ServerWebExchange> {
private final ApiHttpClient apiHttpClient;

private final ServiceRegion serviceRegion;

@Value(value = "${ctp.client.id}")
private String clientId;

Expand All @@ -108,23 +110,24 @@ private ClientCredentials credentials() {
}

@Autowired
public CtpReactiveAuthenticationManagerResolver(final ApiHttpClient apiHttpClient) {
public CtpReactiveAuthenticationManagerResolver(final ApiHttpClient apiHttpClient, final ServiceRegion serviceRegion) {
this.apiHttpClient = apiHttpClient;
this.serviceRegion = serviceRegion;
}

@Override
public Mono<ReactiveAuthenticationManager> resolve(final ServerWebExchange context) {
return Mono.just(new CtpReactiveAuthenticationManager(meClient(apiHttpClient, context.getSession()),
credentials(), projectKey));
credentials(), projectKey, serviceRegion));
}

private ProjectApiRoot meClient(final ApiHttpClient client, final Mono<WebSession> session) {
TokenStorage storage = new SessionTokenStorage(session);

ApiRootBuilder builder = ApiRootBuilder.of(client)
.withApiBaseUrl(ServiceRegion.GCP_EUROPE_WEST1.getApiUrl())
.withApiBaseUrl(serviceRegion.getApiUrl())
.withProjectKey(projectKey)
.withAnonymousRefreshFlow(credentials(), ServiceRegion.GCP_EUROPE_WEST1, storage);
.withAnonymousRefreshFlow(credentials(), serviceRegion, storage);

return builder.build(projectKey);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,13 +35,16 @@ public class MeClientFilter implements WebFilter {
@Value(value = "${ctp.project.key}")
private String projectKey;

private final ServiceRegion serviceRegion;

private ClientCredentials credentials() {
return ClientCredentials.of().withClientId(clientId).withClientSecret(clientSecret).build();
}

@Autowired
public MeClientFilter(ApiHttpClient client) {
public MeClientFilter(final ApiHttpClient client, final ServiceRegion serviceRegion) {
this.client = client;
this.serviceRegion = serviceRegion;
}

@Override
Expand All @@ -59,9 +62,9 @@ private ProjectApiRoot meClient(ApiHttpClient client, Mono<WebSession> session)
TokenStorage storage = new SessionTokenStorage(session);

ApiRootBuilder builder = ApiRootBuilder.of(client)
.withApiBaseUrl(ServiceRegion.GCP_EUROPE_WEST1.getApiUrl())
.withApiBaseUrl(serviceRegion.getApiUrl())
.withProjectKey(projectKey)
.withAnonymousRefreshFlow(credentials(), ServiceRegion.GCP_EUROPE_WEST1, storage)
.withAnonymousRefreshFlow(credentials(), serviceRegion, storage)
.withTelemetryMiddleware(new DatadogMiddleware(ApiClient.getDefaultApiClient()))
.withSerializer(new DatadogResponseSerializer(ResponseSerializer.of(), ApiClient.getDefaultApiClient()));

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import com.commercetools.api.client.ProjectApiRoot;
import com.commercetools.api.defaultconfig.ApiRootBuilder;
import com.commercetools.api.defaultconfig.ServiceRegion;
import com.commercetools.monitoring.datadog.DatadogMiddleware;
import com.commercetools.monitoring.datadog.DatadogResponseSerializer;
import com.datadog.api.client.ApiClient;
Expand All @@ -15,6 +16,8 @@
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Optional;

@Configuration
@EnableAutoConfiguration
public class CtpClientBeanService {
Expand All @@ -28,14 +31,22 @@ public class CtpClientBeanService {
@Value(value = "${ctp.project.key}")
private String projectKey;

@Value(value = "${ctp.service.region:#{null}}")
private String serviceRegion;

@Bean
public ServiceRegion serviceRegion() {
return ServiceRegion.valueOf(Optional.ofNullable(this.serviceRegion).orElse("GCP_EUROPE_WEST1"));
}

private ClientCredentials credentials() {
return ClientCredentials.of().withClientId(clientId).withClientSecret(clientSecret).build();
}

@Bean
public ApiHttpClient client() {
ApiRootBuilder builder = ApiRootBuilder.of()
.defaultClient(credentials())
.defaultClient(credentials(), serviceRegion())
.withTelemetryMiddleware(new DatadogMiddleware(ApiClient.getDefaultApiClient()))
.withSerializer(new DatadogResponseSerializer(ResponseSerializer.of(), ApiClient.getDefaultApiClient()));
return builder.buildClient();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import reactor.core.publisher.Mono;

public class CtpReactiveAuthenticationManager implements ReactiveAuthenticationManager {
private final ServiceRegion serviceRegion;
VrapHttpClient client;
ProjectApiRoot apiRoot;

Expand All @@ -32,11 +33,12 @@ public class CtpReactiveAuthenticationManager implements ReactiveAuthenticationM
private final String projectKey;

public CtpReactiveAuthenticationManager(final ProjectApiRoot apiRoot, final ClientCredentials credentials,
final String projectKey) {
final String projectKey, final ServiceRegion serviceRegion) {
this.apiRoot = apiRoot;
this.client = HttpClientSupplier.of().get();
this.credentials = credentials;
this.projectKey = projectKey;
this.serviceRegion = serviceRegion;
}

@Override
Expand All @@ -56,7 +58,7 @@ public Mono<Authentication> authenticate(Authentication authentication) {
GlobalCustomerPasswordTokenSupplier supplier = new GlobalCustomerPasswordTokenSupplier(
credentials.getClientId(), credentials.getClientSecret(), authentication.getName(),
authentication.getCredentials().toString(), null,
ServiceRegion.GCP_EUROPE_WEST1.getPasswordFlowTokenURL(projectKey), client);
serviceRegion.getPasswordFlowTokenURL(projectKey), client);

return Mono.zip(Mono.fromFuture(supplier.getToken().exceptionally(throwable -> null)),
Mono.just(customerSignInResultApiHttpResponse.getBody()));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,16 @@

import com.commercetools.api.client.ProjectScopedApiRoot;
import com.commercetools.api.defaultconfig.ApiRootBuilder;
import com.commercetools.api.defaultconfig.ServiceRegion;
import io.vrap.rmf.base.client.oauth2.ClientCredentials;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Optional;

@Configuration
@EnableAutoConfiguration
public class CtpClientBeanService {
Expand All @@ -23,14 +26,22 @@ public class CtpClientBeanService {
@Value(value = "${ctp.project.key}")
private String projectKey;

@Value(value = "${ctp.service.region:#{null}}")
private String serviceRegion;

private ClientCredentials credentials() {
return ClientCredentials.of().withClientId(clientId).withClientSecret(clientSecret).build();
}

@Bean
public ServiceRegion serviceRegion() {
return ServiceRegion.valueOf(Optional.ofNullable(this.serviceRegion).orElse("GCP_EUROPE_WEST1"));
}

@Bean
public ProjectScopedApiRoot apiRoot() {
ApiRootBuilder builder = ApiRootBuilder.of()
.defaultClient(credentials());
.defaultClient(credentials(), serviceRegion());
return builder.build(projectKey);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import com.commercetools.api.client.ProjectScopedApiRoot;
import com.commercetools.api.defaultconfig.ApiRootBuilder;

import com.commercetools.api.defaultconfig.ServiceRegion;
import com.commercetools.monitoring.newrelic.NewRelicContext;
import com.commercetools.monitoring.newrelic.NewRelicTelemetryMiddleware;
import com.commercetools.monitoring.newrelic.NewrelicResponseSerializer;
Expand All @@ -19,6 +20,8 @@
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.annotation.RequestScope;

import java.util.Optional;

@Configuration
@EnableAutoConfiguration
public class CtpClientBeanService {
Expand All @@ -32,14 +35,22 @@ public class CtpClientBeanService {
@Value(value = "${ctp.project.key}")
private String projectKey;

@Value(value = "${ctp.service.region:#{null}}")
private String serviceRegion;

private ClientCredentials credentials() {
return ClientCredentials.of().withClientId(clientId).withClientSecret(clientSecret).build();
}

@Bean
public ServiceRegion serviceRegion() {
return ServiceRegion.valueOf(Optional.ofNullable(this.serviceRegion).orElse("GCP_EUROPE_WEST1"));
}

@Bean
public ApiHttpClient client() {
return ApiRootBuilder.of()
.defaultClient(credentials())
.defaultClient(credentials(), serviceRegion())
.withTelemetryMiddleware(new NewRelicTelemetryMiddleware())
.withSerializer(new NewrelicResponseSerializer(ResponseSerializer.of()))
.buildClient();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import com.commercetools.api.client.ProjectScopedApiRoot;
import com.commercetools.api.defaultconfig.ApiRootBuilder;

import com.commercetools.api.defaultconfig.ServiceRegion;
import com.commercetools.monitoring.opentelemetry.OpenTelemetryMiddleware;
import com.commercetools.monitoring.opentelemetry.OpenTelemetryResponseSerializer;
import io.opentelemetry.api.GlobalOpenTelemetry;
Expand All @@ -17,6 +18,8 @@
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.annotation.RequestScope;

import java.util.Optional;

@Configuration
@EnableAutoConfiguration
public class CtpClientBeanService {
Expand All @@ -33,14 +36,22 @@ public class CtpClientBeanService {
@Value(value = "${otel.provider:local}")
private OtelProvider otelProvider;

@Value(value = "${ctp.service.region:#{null}}")
private String serviceRegion;

private ClientCredentials credentials() {
return ClientCredentials.of().withClientId(clientId).withClientSecret(clientSecret).build();
}

@Bean
public ServiceRegion serviceRegion() {
return ServiceRegion.valueOf(Optional.ofNullable(this.serviceRegion).orElse("GCP_EUROPE_WEST1"));
}

@Bean
public ProjectScopedApiRoot apiRoot() {
ApiRootBuilder builder = ApiRootBuilder.of()
.defaultClient(credentials())
.defaultClient(credentials(), serviceRegion())
.withTelemetryMiddleware(new OpenTelemetryMiddleware(GlobalOpenTelemetry.get(),
otelProvider.supportsHistogram()));
if (otelProvider.useOtelSerializer()) {
Expand Down
6 changes: 5 additions & 1 deletion examples/spring/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,11 @@ Example to show how the ME endpoints can be used with the Java SDK in a Spring B
2. Navigate to the path `spring/`.
3. Register the client credentials in environment variables:
`CTP_CLIENT_ID`, `CTP_CLIENT_SECRET` and `CTP_PROJECT_KEY`
4. If your [project region](https://docs.commercetools.com/api/general-concepts#regions) is not GCP Europe, then register [API URL](https://docs.commercetools.com/api/general-concepts#hosts) and [Auth URL](https://docs.commercetools.com/api/authorization#requesting-an-access-token-using-the-composable-commerce-oauth-20-service) in environment variables: `CTP_PROJECT_API_BASE_URL`, `CTP_PROJECT_AUTH_URL`
4. If your [project region](https://docs.commercetools.com/api/general-concepts#regions) is not GCP Europe, then register
[API URL](https://docs.commercetools.com/api/general-concepts#hosts) and [Auth URL](https://docs.commercetools.com/api/authorization#requesting-an-access-token-using-the-composable-commerce-oauth-20-service)
in environment variables: `CTP_PROJECT_API_BASE_URL`, `CTP_PROJECT_AUTH_URL`
**or**
register the service region in the environment variable `CTP_SERVICE_REGION`

## Using the ME Endpoint Checkout App

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -110,34 +110,37 @@ public static class CtpReactiveAuthenticationManagerResolver
@Value(value = "${ctp.project.auth.url:#{null}}")
private String authUrl;

private final ServiceRegion serviceRegion;

private ClientCredentials credentials() {
return ClientCredentials.of().withClientId(clientId).withClientSecret(clientSecret).build();
}

@Autowired
public CtpReactiveAuthenticationManagerResolver(final ApiHttpClient apiHttpClient) {
public CtpReactiveAuthenticationManagerResolver(final ApiHttpClient apiHttpClient, final ServiceRegion serviceRegion) {
this.apiHttpClient = apiHttpClient;
this.serviceRegion = serviceRegion;
}

@Override
public Mono<ReactiveAuthenticationManager> resolve(final ServerWebExchange context) {
return Mono.just(new CtpReactiveAuthenticationManager(meClient(apiHttpClient, context.getSession()),
credentials(), projectKey, authUrl));
credentials(), projectKey, authUrl, serviceRegion));
}

private ProjectApiRoot meClient(final ApiHttpClient client, final Mono<WebSession> session) {
TokenStorage storage = new SessionTokenStorage(session);

ApiRootBuilder builder = ApiRootBuilder.of(client)
.withApiBaseUrl(apiBaseUrl != null ? apiBaseUrl : ServiceRegion.GCP_EUROPE_WEST1.getApiUrl())
.withApiBaseUrl(apiBaseUrl != null ? apiBaseUrl : serviceRegion.getApiUrl())
.withProjectKey(projectKey);

if (authUrl != null) {
builder = builder.withAnonymousRefreshFlow(credentials(),
authUrl + "/oauth/" + projectKey + "/anonymous/token", authUrl + "/oauth/token", storage);
}
else {
builder = builder.withAnonymousRefreshFlow(credentials(), ServiceRegion.GCP_EUROPE_WEST1, storage);
builder = builder.withAnonymousRefreshFlow(credentials(), serviceRegion, storage);
}

return builder.build(projectKey);
Expand Down
Loading

0 comments on commit 4c387e5

Please sign in to comment.