From 2f05389e0164905625666229261a6c3ee8d50838 Mon Sep 17 00:00:00 2001 From: Nagesh Dixit Date: Mon, 29 Jan 2024 12:34:13 -0500 Subject: [PATCH 1/2] updated to sdk version 17.5 --- build.gradle | 7 +- src/main/java/handson/Task02a_CREATE.java | 3 +- .../java/handson/Task02b_UPDATE_Group.java | 3 +- src/main/java/handson/Task03b_IMPORT_API.java | 5 +- .../java/handson/Task03c_SYNC_PROJECTS.java | 2 +- .../java/handson/Task04a_STATEMACHINE.java | 61 +++++---- src/main/java/handson/Task04b_CHECKOUT.java | 7 +- .../java/handson/Task04c_CART_MERGING.java | 34 +++-- src/main/java/handson/Task05a_INSTORE_ME.java | 129 ------------------ src/main/java/handson/Task05a_STORES.java | 63 +++++++++ .../handson/Task05b_PRODUCTSELECTIONS.java | 19 ++- src/main/java/handson/Task05c_ME.java | 90 ++++++++++++ src/main/java/handson/Task06a_SEARCH.java | 2 +- src/main/java/handson/Task06b_PAGEDQUERY.java | 2 +- src/main/java/handson/Task06c_GRAPHQL.java | 2 +- .../java/handson/Task07a_CUSTOMTYPES.java | 6 +- .../java/handson/Task07b_CUSTOMOBJECTS.java | 44 +++--- .../java/handson/Task07c_APIEXTENSION.java | 55 ++++---- .../java/handson/Task08a_SUBSCRIPTION.java | 58 ++++---- .../java/handson/Task09a_ERROR_HANDLING.java | 4 +- .../handson/Task09b_SPHERECLIENT_LOGGING.java | 11 +- src/main/java/handson/impl/CartService.java | 2 +- .../java/handson/impl/CustomerService.java | 51 ++++--- src/main/java/handson/impl/ImportService.java | 12 +- src/main/java/handson/impl/OrderService.java | 2 +- .../java/handson/impl/PaymentService.java | 97 ++++++------- .../handson/impl/ProductSelectionService.java | 21 +-- .../handson/impl/StateMachineService.java | 22 ++- src/main/resources/logback.xml | 2 +- 29 files changed, 405 insertions(+), 411 deletions(-) delete mode 100644 src/main/java/handson/Task05a_INSTORE_ME.java create mode 100644 src/main/java/handson/Task05a_STORES.java create mode 100644 src/main/java/handson/Task05c_ME.java diff --git a/build.gradle b/build.gradle index 34b461d..f92ab35 100644 --- a/build.gradle +++ b/build.gradle @@ -20,9 +20,9 @@ plugins { ext { versions = [ - commercetools: "14.5.0", - slf4j: "1.7.36", - logback: "1.2.10", + commercetools: "17.5.0", + slf4j: "2.0.11", + logback: "1.4.14", ] } @@ -46,7 +46,6 @@ dependencies { implementation "com.commercetools.sdk:commercetools-sdk-java-api:${versions.commercetools}" implementation "com.commercetools.sdk:commercetools-graphql-api:${versions.commercetools}" implementation "com.commercetools.sdk:commercetools-sdk-java-importapi:${versions.commercetools}" - implementation "com.commercetools.sdk:commercetools-sdk-java-ml:${versions.commercetools}" implementation "org.slf4j:slf4j-api:${versions.slf4j}" implementation "ch.qos.logback:logback-classic:${versions.logback}" diff --git a/src/main/java/handson/Task02a_CREATE.java b/src/main/java/handson/Task02a_CREATE.java index 419f826..6da46b7 100644 --- a/src/main/java/handson/Task02a_CREATE.java +++ b/src/main/java/handson/Task02a_CREATE.java @@ -29,7 +29,8 @@ public static void main(String[] args) throws IOException, ExecutionException, I */ final String apiClientPrefix = ApiPrefixHelper.API_DEV_CLIENT_PREFIX.getPrefix(); - Logger logger = LoggerFactory.getLogger(Task02a_CREATE.class.getName()); + Logger logger = LoggerFactory.getLogger("commercetools"); + final ProjectApiRoot client = createApiClient(apiClientPrefix); CustomerService customerService = new CustomerService(client); diff --git a/src/main/java/handson/Task02b_UPDATE_Group.java b/src/main/java/handson/Task02b_UPDATE_Group.java index 35e9d21..f256375 100644 --- a/src/main/java/handson/Task02b_UPDATE_Group.java +++ b/src/main/java/handson/Task02b_UPDATE_Group.java @@ -26,7 +26,8 @@ public static void main(String[] args) throws IOException, ExecutionException, I final String apiClientPrefix = ApiPrefixHelper.API_DEV_CLIENT_PREFIX.getPrefix(); - Logger logger = LoggerFactory.getLogger(Task02b_UPDATE_Group.class.getName()); + Logger logger = LoggerFactory.getLogger("commercetools"); + final ProjectApiRoot client = createApiClient(apiClientPrefix); CustomerService customerService = new CustomerService(client); diff --git a/src/main/java/handson/Task03b_IMPORT_API.java b/src/main/java/handson/Task03b_IMPORT_API.java index bb06b69..7e3f0b6 100644 --- a/src/main/java/handson/Task03b_IMPORT_API.java +++ b/src/main/java/handson/Task03b_IMPORT_API.java @@ -25,10 +25,11 @@ public static void main(String[] args) throws IOException, ExecutionException, I // Provide a container key // final String apiImportClientPrefix = ApiPrefixHelper.API_DEV_IMPORT_PREFIX.getPrefix(); - final String containerKey = "mh-berlin-store-prices"; - Logger logger = LoggerFactory.getLogger(Task02b_UPDATE_Group.class.getName()); + Logger logger = LoggerFactory.getLogger("commercetools"); final ProjectApiRoot client = createImportApiClient(apiImportClientPrefix); + + final String containerKey = "mh-berlin-store-prices"; final ImportService importService = new ImportService(client); diff --git a/src/main/java/handson/Task03c_SYNC_PROJECTS.java b/src/main/java/handson/Task03c_SYNC_PROJECTS.java index afb1520..d61ea5e 100644 --- a/src/main/java/handson/Task03c_SYNC_PROJECTS.java +++ b/src/main/java/handson/Task03c_SYNC_PROJECTS.java @@ -15,7 +15,7 @@ public class Task03c_SYNC_PROJECTS { public static void main(String[] args) throws IOException, InterruptedException { - Logger logger = LoggerFactory.getLogger(Task02b_UPDATE_Group.class.getName()); + Logger logger = LoggerFactory.getLogger("commercetools"); // TODO // Have docker installed diff --git a/src/main/java/handson/Task04a_STATEMACHINE.java b/src/main/java/handson/Task04a_STATEMACHINE.java index 7dbc8d4..e4aa4e5 100644 --- a/src/main/java/handson/Task04a_STATEMACHINE.java +++ b/src/main/java/handson/Task04a_STATEMACHINE.java @@ -6,11 +6,13 @@ import com.commercetools.api.models.state.StateTypeEnum; import handson.impl.ApiPrefixHelper; import handson.impl.StateMachineService; +import io.vrap.rmf.base.client.ApiHttpResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.ArrayList; +import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -28,39 +30,38 @@ public static void main(String[] args) throws IOException, ExecutionException, I final ProjectApiRoot client = createApiClient(apiClientPrefix); final StateMachineService stateMachineService = new StateMachineService(client); - // TODO - // Use StateMachineService.java to create your designed order state machine + // TODO Use StateMachineService.java to create your designed order state machine // - State orderPackedState = - stateMachineService.createState("mhOrderPacked", StateTypeEnum.ORDER_STATE, true, "MH Order Packed") - .toCompletableFuture().get() - .getBody(); - State orderShippedState = - stateMachineService.createState("mhOrderShipped", StateTypeEnum.ORDER_STATE, false, "MH Order Shipped") - .toCompletableFuture().get() - .getBody(); - logger.info("State info {}", - stateMachineService.setStateTransitions( - orderPackedState, - Stream.of( - StateResourceIdentifierBuilder.of(). - id(orderShippedState.getId()) - .build() - ) - .collect(Collectors.toList()) + stateMachineService.createState("mh1OrderPacked", StateTypeEnum.ORDER_STATE, true, "MH1 Order Packed") + .thenCombineAsync(stateMachineService.createState("mh1OrderShipped", StateTypeEnum.ORDER_STATE, false, "MH1 Order Shipped"), + (orderPackedStateApiResponse, orderShippedStateApiResponse)-> + stateMachineService.setStateTransitions( + orderPackedStateApiResponse.getBody(), + Stream.of( + StateResourceIdentifierBuilder.of(). + id(orderShippedStateApiResponse.getBody().getId()) + .build() + ) + .collect(Collectors.toList()) + ) + .thenComposeAsync(apiHttpResponse -> + stateMachineService.setStateTransitions( + orderShippedStateApiResponse.getBody(), + new ArrayList<>() + ) + ) ) - .toCompletableFuture().get() - ); - - logger.info("State info {}", - stateMachineService.setStateTransitions( - orderShippedState, - new ArrayList<>() - ) - .toCompletableFuture().get() - ); + .get() + .thenApply(ApiHttpResponse::getBody) + .thenAccept(resource -> logger.info("State info {}",resource.getId())) + .exceptionally(exception -> { + logger.info("An error occured " + exception.getMessage()); + return null;} + ) + .thenRun(() -> client.close()); - client.close(); + // TODO Create an order in the Merchant Center and verify that custom workflow states are available + // } } diff --git a/src/main/java/handson/Task04b_CHECKOUT.java b/src/main/java/handson/Task04b_CHECKOUT.java index a5b1293..3af6f44 100644 --- a/src/main/java/handson/Task04b_CHECKOUT.java +++ b/src/main/java/handson/Task04b_CHECKOUT.java @@ -26,19 +26,20 @@ public static void main(String[] args) throws IOException, ExecutionException, I final String apiClientPrefix = ApiPrefixHelper.API_DEV_CLIENT_PREFIX.getPrefix(); final ProjectApiRoot client = createApiClient(apiClientPrefix); + Logger logger = LoggerFactory.getLogger("commercetools"); CustomerService customerService = new CustomerService(client); CartService cartService = new CartService(client); OrderService orderService = new OrderService(client); PaymentService paymentService = new PaymentService(client); - Logger logger = LoggerFactory.getLogger(Task04b_CHECKOUT.class.getName()); + // TODO: Fetch a channel if your inventory mode will not be NONE // - Channel channel = null; + final String channelKey = ""; - final State state = null; + final String initialStateKey = ""; // TODO: Perform cart operations: diff --git a/src/main/java/handson/Task04c_CART_MERGING.java b/src/main/java/handson/Task04c_CART_MERGING.java index d2a076c..d5a7429 100644 --- a/src/main/java/handson/Task04c_CART_MERGING.java +++ b/src/main/java/handson/Task04c_CART_MERGING.java @@ -10,6 +10,7 @@ import java.io.IOException; import java.util.concurrent.ExecutionException; +import java.util.stream.Collectors; import static com.commercetools.api.models.customer.AnonymousCartSignInMode.MERGE_WITH_EXISTING_CUSTOMER_CART; import static handson.impl.ClientService.createApiClient; @@ -25,31 +26,44 @@ public static void main(String[] args) throws IOException, ExecutionException, I CustomerService customerService = new CustomerService(client); CartService cartService = new CartService(client); - Logger logger = LoggerFactory.getLogger(Task04c_CART_MERGING.class.getName()); + Logger logger = LoggerFactory.getLogger("commercetools"); + + final String customerKey = "customer-michael15"; + final String channelKey = "berlin-store-channel"; // TODO: Inspect cart merging // Complete the checkout by adding products, payment, ... test // Get a customer and create a cart for this customer // - final Cart cart = customerService.getCustomerByKey("customer-michael15") + final Cart customerCart = customerService.getCustomerByKey(customerKey) .thenComposeAsync(cartService::createCart) - .toCompletableFuture().get() + .thenComposeAsync(cartApiHttpResponse -> cartService.addProductToCartBySkusAndChannel( + cartApiHttpResponse, + channelKey, + "TULIPSEED01", "TULIPSEED01", "TULIPSEED02" + )) + .get() .getBody(); - logger.info("cart-id: " + cart.getId()); + logger.info("cart-id: " + customerCart.getId()); // Create an anonymous cart // Cart anonymousCart = cartService.createAnonymousCart() - .toCompletableFuture().get() + .thenComposeAsync(cartApiHttpResponse -> cartService.addProductToCartBySkusAndChannel( + cartApiHttpResponse, + channelKey, + "TULIPSEED01" + )) + .get() .getBody(); logger.info("cart-id-anonymous: " + anonymousCart.getId()); // TODO: Decide on a merging strategy // - String cartString = client + final Cart cart = client .login() .post( CustomerSigninBuilder.of() @@ -62,11 +76,11 @@ public static void main(String[] args) throws IOException, ExecutionException, I .build() ) .execute() - .toCompletableFuture().get().getBody().getCart().getId(); - logger.info("cart-id-after_merge: " + cartString); + .get().getBody().getCart(); - // TODO: Inspect the customers carts here or via impex - // + logger.info("cart ID in use after merge: " + cart.getId()); + + cart.getLineItems().forEach(lineItem -> logger.info(lineItem.getVariant().getSku())); client.close(); } diff --git a/src/main/java/handson/Task05a_INSTORE_ME.java b/src/main/java/handson/Task05a_INSTORE_ME.java deleted file mode 100644 index 8f7f5d2..0000000 --- a/src/main/java/handson/Task05a_INSTORE_ME.java +++ /dev/null @@ -1,129 +0,0 @@ -package handson; - -import com.commercetools.api.client.ProjectApiRoot; -import com.commercetools.api.models.cart.CartDraftBuilder; -import com.commercetools.api.models.me.MyCartDraftBuilder; -import handson.impl.ApiPrefixHelper; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.util.concurrent.ExecutionException; - -import static handson.impl.ClientService.createApiClient; -import static handson.impl.ClientService.createStoreMeApiClient; -import static handson.impl.ClientService.createMeTokenApiClient; - - -/** - * - */ -public class Task05a_INSTORE_ME { - - public static void main(String[] args) throws IOException, ExecutionException, InterruptedException { - - Logger logger = LoggerFactory.getLogger(Task05a_INSTORE_ME.class.getName()); - - // TODO: Create in-store cart with global API client - // Provide an API client with global permissions - // Provide a customer who is restricted to a store - // Note: A global cart creation should fail but an in-store cart should world - // - final String globalApiClientPrefix = ApiPrefixHelper.API_DEV_CLIENT_PREFIX.getPrefix(); - final ProjectApiRoot client = createApiClient(globalApiClientPrefix); - - logger.info("Created in-store cart with a global api client: " + - " " - ); - client.close(); - - // TODO: Create in-store Cart with in-store API client - // Update the ApiPrefixHelper with the prefix for Store API Client - // Provide an API client with scope limited to a store - // Provide a customer with only store permissions - // Try creating a global cart with a global customer and check the error message - -// final String storeApiClientPrefix = ApiPrefixHelper.API_STORE_CLIENT_PREFIX.getPrefix(); -// final String storeKey = getStoreKey(storeApiClientPrefix); -// final ProjectApiRoot storeClient = createApiClient(storeApiClientPrefix); - - logger.info("Created in-store cart with a store api client: "+ - " " - ); -// storeClient.close(); - - // TODO - // Verify on impex that the carts are holding the same information - // - - - - - // TODO: Create a cart via /me endpoint - // Provide API client with SPA for customer with global permissions - // Update the ApiPrefixHelper with the prefix for Me(SPA) API Client - // You can also create in-store customer-bound cart - // Visit impex to inspect the carts created - -// final String meApiClientPrefix = ApiPrefixHelper.API_ME_CLIENT_PREFIX.getPrefix(); -// final ProjectApiRoot meClient = createMeTokenApiClient(meApiClientPrefix); -// final String customerEmail = getCustomerEmail(meApiClientPrefix); - -// logger.info("Get cart for customer via me endpoint: " + -// meClient -// .me() -// .carts() -// .post( -// MyCartDraftBuilder.of() -// .currency("EUR") -// .deleteDaysAfterLastModification(90L) -// .customerEmail(customerEmail) -// .build() -// ) -// .execute() -// .exceptionally(throwable -> { -// logger.info(throwable.getLocalizedMessage()); -// return null; -// }) -// .toCompletableFuture().get() -// .getBody().getId() -// ); -// meClient.close(); - - // TODO: Create in-store customer-bound Cart with in-store-me API client - // Update the ApiPrefixHelper with the prefix for Me(SPA) API Client - // Provide in-store-me API client with scope for a store and me endpoint - // Try creating a global cart without me and check the error message - // Visit impex to inspect the carts created -// final String storeMeApiClientPrefix = ApiPrefixHelper.API_STORE_ME_CLIENT_PREFIX.getPrefix(); -// final ProjectApiRoot storeClient = createStoreMeApiClient(storeMeApiClientPrefix); -// final String storeKey = getStoreKey(storeMeApiClientPrefix); -// final String storeCustomerEmail = getCustomerEmail(storeMeApiClientPrefix); -// -// logger.info("Created in-store cart with a store api client: "+ -// storeClient -// .inStore(storeKey) -// .me() -// .carts() -// .post( -// MyCartDraftBuilder.of() -// .deleteDaysAfterLastModification(90L) -// .currency("EUR") -// .customerEmail(storeCustomerEmail) -// .build() -// ) -// .execute() -// .exceptionally(throwable -> { -// logger.info(throwable.getLocalizedMessage().toString()); -// return null; -// }) -// .toCompletableFuture().get() -// .getBody().getId() -// ); -// storeClient.close(); - - - - } -} diff --git a/src/main/java/handson/Task05a_STORES.java b/src/main/java/handson/Task05a_STORES.java new file mode 100644 index 0000000..dba631a --- /dev/null +++ b/src/main/java/handson/Task05a_STORES.java @@ -0,0 +1,63 @@ +package handson; + +import com.commercetools.api.client.ProjectApiRoot; +import handson.impl.ApiPrefixHelper; + +import handson.impl.CustomerService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.util.concurrent.ExecutionException; + +import static handson.impl.ClientService.createApiClient; + + +/** + * + */ +public class Task05a_STORES { + + public static void main(String[] args) throws IOException, ExecutionException, InterruptedException { + + Logger logger = LoggerFactory.getLogger("commercetools"); + + final String customerKey = ""; + final String storeKey = ""; + + // TODO: Create in-store cart with global API client + // 1. Provide an API client with global permissions + // 2. Provide a customer who is restricted to a store + // Note: A global cart creation should fail but an in-store cart should world + // + final String globalApiClientPrefix = ApiPrefixHelper.API_DEV_CLIENT_PREFIX.getPrefix(); + final ProjectApiRoot client = createApiClient(globalApiClientPrefix); + + CustomerService customerService = new CustomerService(client); + + logger.info("Created in-store cart with a global api client: " + + " " + ); + + + // TODO: Create in-store Cart with in-store API client + // 1. Update the ApiPrefixHelper with the prefix for Store API Client + // 2. Provide an API client with scope limited to a store + // 3. Provide a customer with only store permissions + // 4. Try creating a global cart with a global customer and check the error message + +// final String storeApiClientPrefix = ApiPrefixHelper.API_STORE_CLIENT_PREFIX.getPrefix(); +// final ProjectApiRoot storeClient = createApiClient(storeApiClientPrefix); + + logger.info("Created in-store cart with a store api client: "+ + " " + ); + + client.close(); +// storeClient.close(); + + // TODO + // Verify on impex that the carts are holding the same information + + } +} diff --git a/src/main/java/handson/Task05b_PRODUCTSELECTIONS.java b/src/main/java/handson/Task05b_PRODUCTSELECTIONS.java index 2347fd1..33d9364 100644 --- a/src/main/java/handson/Task05b_PRODUCTSELECTIONS.java +++ b/src/main/java/handson/Task05b_PRODUCTSELECTIONS.java @@ -23,25 +23,21 @@ public class Task05b_PRODUCTSELECTIONS { public static void main(String[] args) throws IOException, ExecutionException, InterruptedException { - Logger logger = LoggerFactory.getLogger(Task05b_PRODUCTSELECTIONS.class.getName()); + Logger logger = LoggerFactory.getLogger("commercetools"); final String globalApiClientPrefix = ApiPrefixHelper.API_DEV_CLIENT_PREFIX.getPrefix(); final ProjectApiRoot client = createApiClient(globalApiClientPrefix); final ProductSelectionService productSelectionService = new ProductSelectionService(client); - final String productSelectionKey = "mh-berlin-product-selection"; + // TODO: In Merchant Center, create product selection and add a product to the product selection. + // Update the keys below - // TODO: Create product selection and add a product to the product selection + final String productSelectionKey = ""; + final String storeKey = ""; - ProductSelection productSelection = null; - logger.info("Created product selection: " + productSelection.getId()); + // TODO: Get a store and assign the product selection to the store and activate it - - - // TODO: Get a store and assign the product selection to the store - - - logger.info("Product selections assigned to the store: " + logger.info("Product selection added to the store: " + "" ); @@ -51,5 +47,6 @@ public static void main(String[] args) throws IOException, ExecutionException, I List assignedProductReferences = null; // assignedProductReferences.forEach(assignedProductReference -> logger.info(assignedProductReference.getProduct().getObj().getKey())); + client.close(); } } diff --git a/src/main/java/handson/Task05c_ME.java b/src/main/java/handson/Task05c_ME.java new file mode 100644 index 0000000..2945e68 --- /dev/null +++ b/src/main/java/handson/Task05c_ME.java @@ -0,0 +1,90 @@ +package handson; + +import com.commercetools.api.client.ProjectApiRoot; +import com.commercetools.api.models.me.MyCartDraftBuilder; +import handson.impl.ApiPrefixHelper; +import handson.impl.CustomerService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.util.concurrent.ExecutionException; + +import static handson.impl.ClientService.*; + + +/** + * + */ +public class Task05c_ME { + + public static void main(String[] args) throws IOException, ExecutionException, InterruptedException { + + Logger logger = LoggerFactory.getLogger("commercetools"); + + // TODO: Create a cart via /me endpoint + // Provide API client with SPA for customer with global permissions + // Update the ApiPrefixHelper with the prefix for Me(SPA) API Client + // You can also create in-store customer-bound cart + // Visit impex to inspect the carts created + + final String meApiClientPrefix = ApiPrefixHelper.API_ME_CLIENT_PREFIX.getPrefix(); + final ProjectApiRoot meClient = createMeTokenApiClient(meApiClientPrefix); + final String customerEmail = getCustomerEmail(meApiClientPrefix); + + logger.info("Get cart for customer via me endpoint: " + + meClient + .me() + .carts() + .post( + MyCartDraftBuilder.of() + .currency("EUR") + .deleteDaysAfterLastModification(90L) + .customerEmail(customerEmail) + .build() + ) + .execute() + .exceptionally(throwable -> { + logger.info(throwable.getLocalizedMessage()); + return null; + }) + .toCompletableFuture().get() + .getBody().getId() + ); + meClient.close(); + + // TODO: Create in-store customer-bound Cart with in-store-me API client + // Update the ApiPrefixHelper with the prefix for Me(SPA) API Client + // Provide in-store-me API client with scope for a store and me endpoint + // Try creating a global cart without me and check the error message + // Visit impex to inspect the carts created +// final String storeMeApiClientPrefix = ApiPrefixHelper.API_STORE_ME_CLIENT_PREFIX.getPrefix(); +// final ProjectApiRoot storeMeClient = createStoreMeApiClient(storeMeApiClientPrefix); +// final String storeKey = getStoreKey(storeMeApiClientPrefix); +// final String storeCustomerEmail = getCustomerEmail(storeMeApiClientPrefix); +// +// logger.info("Created in-store cart with a store api client: "+ +// storeMeClient +// .inStore(storeKey) +// .me() +// .carts() +// .post( +// MyCartDraftBuilder.of() +// .deleteDaysAfterLastModification(90L) +// .currency("EUR") +// .customerEmail(storeCustomerEmail) +// .build() +// ) +// .execute() +// .exceptionally(throwable -> { +// logger.info(throwable.getLocalizedMessage().toString()); +// return null; +// }) +// .toCompletableFuture().get() +// .getBody().getId() +// ); +// storeMeClient.close(); + + + } +} diff --git a/src/main/java/handson/Task06a_SEARCH.java b/src/main/java/handson/Task06a_SEARCH.java index a1ef21c..70907a3 100644 --- a/src/main/java/handson/Task06a_SEARCH.java +++ b/src/main/java/handson/Task06a_SEARCH.java @@ -22,7 +22,7 @@ public static void main(String[] args) throws Exception { final String apiClientPrefix = ApiPrefixHelper.API_DEV_CLIENT_PREFIX.getPrefix(); final ProjectApiRoot client = createApiClient(apiClientPrefix); - Logger logger = LoggerFactory.getLogger(Task06a_SEARCH.class.getName()); + Logger logger = LoggerFactory.getLogger("commercetools"); Category seedCategory = client .categories() diff --git a/src/main/java/handson/Task06b_PAGEDQUERY.java b/src/main/java/handson/Task06b_PAGEDQUERY.java index f31fc52..e96cfda 100644 --- a/src/main/java/handson/Task06b_PAGEDQUERY.java +++ b/src/main/java/handson/Task06b_PAGEDQUERY.java @@ -23,7 +23,7 @@ public static void main(String[] args) throws IOException, ExecutionException, I final ProjectApiRoot client = createApiClient(apiClientPrefix); - Logger logger = LoggerFactory.getLogger(Task06b_PAGEDQUERY.class.getName()); + Logger logger = LoggerFactory.getLogger("commercetools"); // UseCases // Fetching ALL products diff --git a/src/main/java/handson/Task06c_GRAPHQL.java b/src/main/java/handson/Task06c_GRAPHQL.java index 399bc8d..8cbeb93 100644 --- a/src/main/java/handson/Task06c_GRAPHQL.java +++ b/src/main/java/handson/Task06c_GRAPHQL.java @@ -23,7 +23,7 @@ public static void main(String[] args) throws IOException, ExecutionException, I final String apiClientPrefix = ApiPrefixHelper.API_DEV_CLIENT_PREFIX.getPrefix(); final ProjectApiRoot client = createApiClient(apiClientPrefix); - Logger logger = LoggerFactory.getLogger(Task04b_CHECKOUT.class.getName()); + Logger logger = LoggerFactory.getLogger("commercetools"); // TODO: diff --git a/src/main/java/handson/Task07a_CUSTOMTYPES.java b/src/main/java/handson/Task07a_CUSTOMTYPES.java index 6ef7679..359f9eb 100644 --- a/src/main/java/handson/Task07a_CUSTOMTYPES.java +++ b/src/main/java/handson/Task07a_CUSTOMTYPES.java @@ -25,7 +25,7 @@ public static void main(String[] args) throws IOException, ExecutionException, I final String apiClientPrefix = ApiPrefixHelper.API_DEV_CLIENT_PREFIX.getPrefix(); final ProjectApiRoot client = createApiClient(apiClientPrefix); - Logger logger = LoggerFactory.getLogger(Task07a_CUSTOMTYPES.class.getName()); + Logger logger = LoggerFactory.getLogger("commercetools"); Map labelsForFieldCheck = new HashMap() { { @@ -44,7 +44,7 @@ public static void main(String[] args) throws IOException, ExecutionException, I List definitions = Arrays.asList( FieldDefinitionBuilder.of() .name("allowed-to-place-orders") - .required(false) + .required(true) .label(LocalizedStringBuilder.of() .values(labelsForFieldCheck) .build() @@ -54,7 +54,7 @@ public static void main(String[] args) throws IOException, ExecutionException, I , FieldDefinitionBuilder.of() .name("Comments") - .required(false) + .required(true) .label(LocalizedStringBuilder.of() .values(labelsForFieldComments) .build() diff --git a/src/main/java/handson/Task07b_CUSTOMOBJECTS.java b/src/main/java/handson/Task07b_CUSTOMOBJECTS.java index 7ea8b02..0501144 100644 --- a/src/main/java/handson/Task07b_CUSTOMOBJECTS.java +++ b/src/main/java/handson/Task07b_CUSTOMOBJECTS.java @@ -1,9 +1,8 @@ package handson; import com.commercetools.api.client.ProjectApiRoot; -import com.commercetools.api.models.custom_object.CustomObjectDraftBuilder; -import com.fasterxml.jackson.databind.ObjectMapper; import handson.impl.ApiPrefixHelper; +import io.vrap.rmf.base.client.ApiHttpResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -22,13 +21,13 @@ public static void main(String[] args) throws IOException, ExecutionException, I final String apiClientPrefix = ApiPrefixHelper.API_DEV_CLIENT_PREFIX.getPrefix(); final ProjectApiRoot client = createApiClient(apiClientPrefix); - Logger logger = LoggerFactory.getLogger(Task07b_CUSTOMOBJECTS.class.getName()); + Logger logger = LoggerFactory.getLogger("commercetools"); // TODO: - // Store custom objects - // container: MH_PlantCheck, Add your prefix - // key: the product variant sku - // incompatibleSKUs: all the product variants above sku is incompatible with + // Create custom objects + // container: plants-compatibility-info + // key: the product key + // incompatibleProducts: all the products that above product is incompatible with JsonObject tulipObject = Json.createObjectBuilder() .add("incompatibleProducts", "basil-seed-product") @@ -43,23 +42,18 @@ public static void main(String[] args) throws IOException, ExecutionException, I ) .build(); - logger.info("Custom Object info: " + - client - .customObjects() - .post( - CustomObjectDraftBuilder.of() - .container("plants-compatibility-info") - .key("tulip-seed-product") - .value( - new ObjectMapper() - .readTree(tulipObject.toString())) - .build() - ) - .execute() - .toCompletableFuture().get() - .getBody().getId() - ); - - client.close(); + client + .customObjects() + .post( + customObjectDraftBuilder -> customObjectDraftBuilder + .container("plants-compatibility-info") + .key("tulip-seed-product") + .value(tulipObject) + ) + .execute() + .thenApply(ApiHttpResponse::getBody) + .thenAccept(resource -> logger.info("Resource ID: " + resource.getId())) + .exceptionally(exception -> { logger.info("An error occured " + exception.getMessage()); return null;}) + .thenRun(() -> client.close()); } } diff --git a/src/main/java/handson/Task07c_APIEXTENSION.java b/src/main/java/handson/Task07c_APIEXTENSION.java index 7a1d024..a51d931 100644 --- a/src/main/java/handson/Task07c_APIEXTENSION.java +++ b/src/main/java/handson/Task07c_APIEXTENSION.java @@ -3,6 +3,7 @@ import com.commercetools.api.client.ProjectApiRoot; import com.commercetools.api.models.extension.*; import handson.impl.ApiPrefixHelper; +import io.vrap.rmf.base.client.ApiHttpResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -19,42 +20,38 @@ public static void main(String[] args) throws IOException, ExecutionException, I final String apiClientPrefix = ApiPrefixHelper.API_DEV_CLIENT_PREFIX.getPrefix(); final ProjectApiRoot client = createApiClient(apiClientPrefix); - Logger logger = LoggerFactory.getLogger(Task07c_APIEXTENSION.class.getName()); - - logger.info("Created extension: " + - client - .extensions() - .post( - ExtensionDraftBuilder.of() - .key("mhCustomerBlocker") - .destination( - // for GCP Cloud functions - GoogleCloudFunctionDestinationBuilder.of() - .url("https://europe-west3-ct-support.cloudfunctions.net/training-extensions-sample") - .build() -// //for AWS Lambda functions + Logger logger = LoggerFactory.getLogger("commercetools"); + + client + .extensions() + .post( + extensionDraftBuilder -> extensionDraftBuilder + .key("mhCustomerBlocker") + .destination( + // for GCP Cloud functions + HttpDestinationBuilder.of() + .url("https://europe-west3-ct-support.cloudfunctions.net/training-extensions-sample") + .build() + //for AWS Lambda functions // ExtensionAWSLambdaDestinationBuilder.of() // .arn("arn:aws:lambda:eu-central-1:923270384842:function:training-customer-check") // .accessKey("AKIAJLJRDGBNBIPY2ZHQ") // .accessSecret("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") // .build() - ) - .triggers( - ExtensionTriggerBuilder.of() - .resourceTypeId(ExtensionResourceTypeId.ORDER) - .actions( - ExtensionAction.CREATE - ) - .build() + ) + .addTriggers(extensionTriggerBuilder -> extensionTriggerBuilder + .resourceTypeId(ExtensionResourceTypeId.ORDER) + .actions( + ExtensionAction.CREATE ) .build() - ) - .execute() - .toCompletableFuture().get() - .getBody().getId() - ); - - client.close(); + ) + ) + .execute() + .thenApply(ApiHttpResponse::getBody) + .thenAccept(resource -> logger.info("Resource ID: " + resource.getId())) + .exceptionally(exception -> { logger.info("An error occured " + exception.getMessage()); return null;}) + .thenRun(() -> client.close()); } } diff --git a/src/main/java/handson/Task08a_SUBSCRIPTION.java b/src/main/java/handson/Task08a_SUBSCRIPTION.java index d1650c5..ee6dabe 100644 --- a/src/main/java/handson/Task08a_SUBSCRIPTION.java +++ b/src/main/java/handson/Task08a_SUBSCRIPTION.java @@ -8,6 +8,7 @@ import com.commercetools.api.models.subscription.MessageSubscriptionResourceTypeId; import com.commercetools.api.models.subscription.SubscriptionDraftBuilder; import handson.impl.ApiPrefixHelper; +import io.vrap.rmf.base.client.ApiHttpResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -27,41 +28,42 @@ public static void main(String[] args) throws IOException, ExecutionException, I final String apiClientPrefix = ApiPrefixHelper.API_DEV_CLIENT_PREFIX.getPrefix(); final ProjectApiRoot client = createApiClient(apiClientPrefix); - Logger logger = LoggerFactory.getLogger(Task08a_SUBSCRIPTION.class.getName()); + Logger logger = LoggerFactory.getLogger("commercetools"); - logger.info("Created subscription: " + - client - .subscriptions() - .post( - SubscriptionDraftBuilder.of() - .key("mhOrderPlacedSubscription") - .destination( - //for GCP Pub/Sub topic - GoogleCloudPubSubDestinationBuilder.of() - .projectId("ct-support") - .topic("training-subscription-sample") - .build() - //for AWS SQS Queue + client + .subscriptions() + .post( + subscriptionDraftBuilder -> subscriptionDraftBuilder + .key("mhOrderPlacedSubscription") + .destination( + //for GCP Pub/Sub topic + GoogleCloudPubSubDestinationBuilder.of() + .projectId("ct-support") + .topic("training-subscription-sample") + .build() + //for AWS SQS Queue // SqsDestinationBuilder.of() // .queueUrl("https://sqs.eu-central-1.amazonaws.com/923270384842/training-customer_change_queue") // .region("eu-central-1") // .accessKey("AKIAJLJRDGBNBIPY2ZHQ") // .accessSecret("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") // .build() - ) - .messages( - MessageSubscriptionBuilder.of() - .resourceTypeId(MessageSubscriptionResourceTypeId.ORDER) // https://docs.commercetools.com/api/types#referencetype - .types("OrderCreated") // https://docs.commercetools.com/api/message-types - .build() - ) - .build() - ) - .execute() - .toCompletableFuture().get() - .getBody() - ); + ) + .addMessages( + messageSubscriptionBuilder -> messageSubscriptionBuilder + .resourceTypeId(MessageSubscriptionResourceTypeId.ORDER) // https://docs.commercetools.com/api/types#referencetype + .types("OrderCreated") // https://docs.commercetools.com/api/message-types + .build() + ) - client.close(); + ) + .execute() + .thenApply(ApiHttpResponse::getBody) + .thenAccept(resource -> logger.info("Resource ID: " + resource.getId())) + .exceptionally(exception -> { + logger.info("An error occured " + exception.getMessage()); + return null;} + ) + .thenRun(() -> client.close()); } } diff --git a/src/main/java/handson/Task09a_ERROR_HANDLING.java b/src/main/java/handson/Task09a_ERROR_HANDLING.java index 560a23a..fb2f70a 100644 --- a/src/main/java/handson/Task09a_ERROR_HANDLING.java +++ b/src/main/java/handson/Task09a_ERROR_HANDLING.java @@ -23,7 +23,7 @@ public static void main(String[] args) throws IOException, ExecutionException, I final String apiClientPrefix = ApiPrefixHelper.API_DEV_CLIENT_PREFIX.getPrefix(); final ProjectApiRoot client = createApiClient(apiClientPrefix); - Logger logger = LoggerFactory.getLogger(Task09a_ERROR_HANDLING.class.getName()); + Logger logger = LoggerFactory.getLogger("commercetools"); CustomerService customerService = new CustomerService(client); @@ -48,7 +48,7 @@ public static void main(String[] args) throws IOException, ExecutionException, I .getCustomerByKey("customer-michele-WRONG-KEY") .thenApply(ApiHttpResponse::getBody) .exceptionally(throwable -> null) - .toCompletableFuture().get() + .get() ); // Handle now diff --git a/src/main/java/handson/Task09b_SPHERECLIENT_LOGGING.java b/src/main/java/handson/Task09b_SPHERECLIENT_LOGGING.java index 67e7334..7cd0b62 100644 --- a/src/main/java/handson/Task09b_SPHERECLIENT_LOGGING.java +++ b/src/main/java/handson/Task09b_SPHERECLIENT_LOGGING.java @@ -31,7 +31,7 @@ public static void main(String[] args) throws IOException, ExecutionException, I final ProjectApiRoot client = createApiClient(apiClientPrefix); final String clientId = getClientId(apiClientPrefix); final String clientSecret = getClientSecret(apiClientPrefix); - Logger logger = LoggerFactory.getLogger(Task09b_SPHERECLIENT_LOGGING.class.getName()); + Logger logger = LoggerFactory.getLogger("commercetools"); // TODO 1..5 // Execute, inspect individually @@ -126,7 +126,7 @@ public static void main(String[] args) throws IOException, ExecutionException, I .get() .withHeader(ApiHttpHeaders.X_CORRELATION_ID, "MyServer15" + UUID.randomUUID()) .execute() - .toCompletableFuture().get() + .get() .getBody().getKey() ); @@ -145,13 +145,14 @@ public static void main(String[] args) throws IOException, ExecutionException, I ServiceRegion.GCP_EUROPE_WEST1.getOAuthTokenUrl(), ServiceRegion.GCP_EUROPE_WEST1.getApiUrl() ) - .withRetryMiddleware(3, Arrays.asList(500, 503)) + .withPolicies(policies -> policies.withRetry(builder -> builder.maxRetries(5) + .statusCodes(Arrays.asList(502, 503, 504, 404, 400)))) .build(projectKey); logger.info("Get project information via retryClient " + retryClient .get() .execute() - .toCompletableFuture().get() + .get() .getBody().getKey() ); @@ -177,7 +178,7 @@ public static void main(String[] args) throws IOException, ExecutionException, I .build()) .build()) .execute() - .toCompletableFuture().get() + .get() .getBody().getLastName() ); concurrentClient.close(); diff --git a/src/main/java/handson/impl/CartService.java b/src/main/java/handson/impl/CartService.java index c571b64..5fa2f96 100644 --- a/src/main/java/handson/impl/CartService.java +++ b/src/main/java/handson/impl/CartService.java @@ -69,7 +69,7 @@ public CompletableFuture> createAnonymousCart() { public CompletableFuture> addProductToCartBySkusAndChannel( final ApiHttpResponse cartApiHttpResponse, - final Channel channel, + final String channelKey, final String ... skus) { return null; diff --git a/src/main/java/handson/impl/CustomerService.java b/src/main/java/handson/impl/CustomerService.java index e6855d6..286ea5b 100644 --- a/src/main/java/handson/impl/CustomerService.java +++ b/src/main/java/handson/impl/CustomerService.java @@ -48,17 +48,18 @@ public CompletableFuture> createEmailVerification null; } - public CompletableFuture> createEmailVerificationToken(final Customer customer, final long timeToLiveInMinutes) { + public CompletableFuture> createEmailVerificationToken( + final Customer customer, + final long timeToLiveInMinutes) { return apiRoot .customers() .emailToken() .post( - CustomerCreateEmailTokenBuilder.of() + customerCreateEmailTokenBuilder -> customerCreateEmailTokenBuilder .id(customer.getId()) .ttlMinutes(timeToLiveInMinutes) - .build() ) .execute(); } @@ -79,10 +80,9 @@ public CompletableFuture> verifyEmail(final CustomerTo .customers() .emailConfirm() .post( - CustomerEmailVerifyBuilder.of() - .tokenValue(customerToken.getValue()) - .build() - ) + customerEmailVerifyBuilder ->customerEmailVerifyBuilder + .tokenValue(customerToken.getValue()) + ) .execute(); } @@ -96,27 +96,24 @@ public CompletableFuture> getCustomerGroupByKey(f } public CompletableFuture> assignCustomerToCustomerGroup( - final ApiHttpResponse customerApiHttpResponse, - final ApiHttpResponse customerGroupApiHttpResponse) { - - final Customer customer = customerApiHttpResponse.getBody(); - final CustomerGroup customerGroup = customerGroupApiHttpResponse.getBody(); - - return - apiRoot - .customers() - .withKey(customer.getKey()) - .post(CustomerUpdateBuilder.of() - .version(customer.getVersion()) - .actions( - CustomerSetCustomerGroupActionBuilder.of() - .customerGroup(CustomerGroupResourceIdentifierBuilder.of() - .key(customerGroup.getKey()) - .build()) - .build() + final String customerKey, + final String customerGroupKey) { + + return getCustomerByKey(customerKey) + .thenComposeAsync(customerApiHttpResponse -> + apiRoot.customers() + .withKey(customerKey) + .post( + customerUpdateBuilder -> customerUpdateBuilder + .version(customerApiHttpResponse.getBody().getVersion()) + .plusActions( + customerUpdateActionBuilder -> customerUpdateActionBuilder + .setCustomerGroupBuilder() + .customerGroup(customerGroupResourceIdentifierBuilder -> customerGroupResourceIdentifierBuilder.key(customerGroupKey)) + ) ) - .build()) - .execute(); + .execute() + ); } } diff --git a/src/main/java/handson/impl/ImportService.java b/src/main/java/handson/impl/ImportService.java index 9f9efa2..1da9713 100644 --- a/src/main/java/handson/impl/ImportService.java +++ b/src/main/java/handson/impl/ImportService.java @@ -27,14 +27,10 @@ public ImportService(final ProjectApiRoot client) { public CompletableFuture> createImportContainer(final String containerKey) { - return + return apiRoot .importContainers() - .post( - ImportContainerDraftBuilder.of() - .key(containerKey) - .build() - ) + .post(importContainerDraftBuilder -> importContainerDraftBuilder.key(containerKey)) .execute(); } @@ -51,8 +47,4 @@ public CompletableFuture> createPriceImportReque null; } - - - - } diff --git a/src/main/java/handson/impl/OrderService.java b/src/main/java/handson/impl/OrderService.java index 3bebed3..bfaac3a 100644 --- a/src/main/java/handson/impl/OrderService.java +++ b/src/main/java/handson/impl/OrderService.java @@ -46,7 +46,7 @@ public CompletableFuture> changeState( public CompletableFuture> changeWorkflowState( final ApiHttpResponse orderApiHttpResponse, - final State workflowState) { + final String customStateKey) { return null; } diff --git a/src/main/java/handson/impl/PaymentService.java b/src/main/java/handson/impl/PaymentService.java index 16a7479..9a37788 100644 --- a/src/main/java/handson/impl/PaymentService.java +++ b/src/main/java/handson/impl/PaymentService.java @@ -44,79 +44,66 @@ public CompletableFuture> createPaymentAndAddToCart( apiRoot .payments() .post( - PaymentDraftBuilder.of() + paymentDraftBuilder -> paymentDraftBuilder .amountPlanned( - MoneyBuilder.of() - .centAmount(cart.getTotalPrice().getCentAmount()) - .currencyCode(cart.getTotalPrice().getCurrencyCode()) - .build() + moneyBuilder -> moneyBuilder + .centAmount(cart.getTotalPrice().getCentAmount()) + .currencyCode(cart.getTotalPrice().getCurrencyCode()) ) .paymentMethodInfo( - PaymentMethodInfoBuilder.of() + paymentMethodInfoBuilder -> paymentMethodInfoBuilder .paymentInterface(psp_Name) // PSP Provider Name: WireCard, .... .method(psp_Method) // PSP Provider Method: CreditCard - .build()) + ) .interfaceId(interfaceId) // ID of the payment, important !!! - .build() ) .execute() .thenComposeAsync(paymentApiHttpResponse -> - apiRoot - .payments() - .withId(paymentApiHttpResponse.getBody().getId()) - .post( - PaymentUpdateBuilder.of() - .version(paymentApiHttpResponse.getBody().getVersion()) - .actions( - PaymentAddTransactionActionBuilder.of() + apiRoot + .payments() + .withId(paymentApiHttpResponse.getBody().getId()) + .post( + paymentUpdateBuilder -> paymentUpdateBuilder + .version(paymentApiHttpResponse.getBody().getVersion()) + .plusActions( + paymentUpdateActionBuilder -> paymentUpdateActionBuilder.addTransactionBuilder() .transaction( - TransactionDraftBuilder.of() + transactionDraftBuilder -> transactionDraftBuilder .amount( - MoneyBuilder.of() + moneyBuilder -> moneyBuilder .centAmount(cart.getTotalPrice().getCentAmount()) .currencyCode(cart.getTotalPrice().getCurrencyCode()) - .build() ) - .timestamp(ZonedDateTime.now()) - .type(TransactionType.CHARGE) - .interactionId(interactionId) - .build() + .timestamp(ZonedDateTime.now()) + .type(TransactionType.CHARGE) + .interactionId(interactionId) ) - .build(), - - // PaymentAddInterfaceInteractionActionBuilder.of() // Requires custom fields - - PaymentSetStatusInterfaceCodeActionBuilder.of() + ) + .plusActions( + paymentUpdateActionBuilder -> paymentUpdateActionBuilder.setStatusInterfaceCodeBuilder() .interfaceCode("SUCCESS") - .build(), - PaymentSetStatusInterfaceTextActionBuilder.of() + ) + .plusActions( + paymentUpdateActionBuilder -> paymentUpdateActionBuilder.setStatusInterfaceTextBuilder() .interfaceText("We got the money.") - .build() - ) - .build() - ) - .execute() - ) + ) + ) + .execute() + ) .thenComposeAsync(paymentApiHttpResponse -> - apiRoot - .carts() - .withId(cart.getId()) - .post( - CartUpdateBuilder.of() - .version(cart.getVersion()) - .actions( - CartAddPaymentActionBuilder.of() - .payment( - PaymentResourceIdentifierBuilder.of() - .id(paymentApiHttpResponse.getBody().getId()) - .build() - ) - .build() - ) - .build() - ) - .execute() - ); + apiRoot + .carts() + .withId(cart.getId()) + .post( + cartUpdateBuilder -> cartUpdateBuilder + .version(cart.getVersion()) + .plusActions( + cartUpdateActionBuilder -> cartUpdateActionBuilder.addPaymentBuilder() + .payment(paymentResourceIdentifierBuilder -> paymentResourceIdentifierBuilder.id(paymentApiHttpResponse.getBody().getId())) + ) + ) + .execute() + ); } } diff --git a/src/main/java/handson/impl/ProductSelectionService.java b/src/main/java/handson/impl/ProductSelectionService.java index 19a457c..9edc305 100644 --- a/src/main/java/handson/impl/ProductSelectionService.java +++ b/src/main/java/handson/impl/ProductSelectionService.java @@ -53,28 +53,17 @@ public CompletableFuture> getStoreByKey(final String stor .execute(); } - /** - * Creates a new product selection. - * - * @return the product selection creation completion stage - */ - public CompletableFuture> createProductSelection(final String productSelectionKey, final String name) { - return - null; - } - - - public CompletableFuture> addProductToProductSelection( - final ApiHttpResponse productSelectionApiHttpResponse, - final String productKey) { + public CompletableFuture> addProductSelectionToStore( + final ApiHttpResponse storeApiHttpResponse, + final ApiHttpResponse productSelectionApiHttpResponse) { return null; } public CompletableFuture> addProductSelectionToStore( - final ApiHttpResponse storeApiHttpResponse, - final ApiHttpResponse productSelectionApiHttpResponse) { + final String storeKey, + final String productSelectionKey) { return null; diff --git a/src/main/java/handson/impl/StateMachineService.java b/src/main/java/handson/impl/StateMachineService.java index 7ca1b20..158fc2b 100644 --- a/src/main/java/handson/impl/StateMachineService.java +++ b/src/main/java/handson/impl/StateMachineService.java @@ -31,18 +31,16 @@ public CompletableFuture> createState(final String key, S apiRoot .states() .post( - StateDraftBuilder.of() + stateDraftBuilder -> stateDraftBuilder .key(key) .type(stateTypeEnum) .initial(initial) .name( - LocalizedStringBuilder.of() + localizedStringBuilder -> localizedStringBuilder .values(myNames) - .build()) - .build() + ) ) .execute(); - } public CompletableFuture> setStateTransitions(final State stateToBeUpdated, final List states) { @@ -52,14 +50,12 @@ public CompletableFuture> setStateTransitions(final State .states() .withId(stateToBeUpdated.getId()) .post( - StateUpdateBuilder.of() - .actions( - StateSetTransitionsActionBuilder.of() - .transitions(states) - .build() - ) - .version(stateToBeUpdated.getVersion()) - .build() + stateUpdateBuilder -> stateUpdateBuilder + .version(stateToBeUpdated.getVersion()) + .plusActions( + stateUpdateActionBuilder -> stateUpdateActionBuilder.setTransitionsBuilder() + .transitions(states) + ) ) .execute(); } diff --git a/src/main/resources/logback.xml b/src/main/resources/logback.xml index 5016215..77c0baa 100644 --- a/src/main/resources/logback.xml +++ b/src/main/resources/logback.xml @@ -11,7 +11,7 @@ - + From b9f0d23efefde78f4ab971499f8df12ef62ca584 Mon Sep 17 00:00:00 2001 From: Nagesh Dixit Date: Tue, 6 Feb 2024 13:59:40 -0500 Subject: [PATCH 2/2] updated to sdk version 17.5 --- build.gradle | 8 ++-- .../java/handson/Task04a_STATEMACHINE.java | 47 +++++++++++++++---- .../java/handson/Task07b_CUSTOMOBJECTS.java | 14 ++++-- .../java/handson/Task07c_APIEXTENSION.java | 14 ++++-- .../java/handson/Task08a_SUBSCRIPTION.java | 17 +++---- .../java/handson/impl/ApiPrefixHelper.java | 8 ++-- src/main/java/handson/impl/ClientService.java | 18 ++++++- .../handson/impl/StateMachineService.java | 9 ++++ 8 files changed, 98 insertions(+), 37 deletions(-) diff --git a/build.gradle b/build.gradle index f92ab35..be6dbee 100644 --- a/build.gradle +++ b/build.gradle @@ -8,7 +8,6 @@ plugins { id 'idea' - id 'maven' id 'maven-publish' id 'java' @@ -26,10 +25,9 @@ ext { ] } -allprojects { - apply plugin: 'java' - sourceCompatibility = 1.8 - targetCompatibility = 1.8 +java { + sourceCompatibility = JavaVersion.VERSION_1_8 + sourceCompatibility = JavaVersion.VERSION_1_8 } diff --git a/src/main/java/handson/Task04a_STATEMACHINE.java b/src/main/java/handson/Task04a_STATEMACHINE.java index e4aa4e5..a93d4ba 100644 --- a/src/main/java/handson/Task04a_STATEMACHINE.java +++ b/src/main/java/handson/Task04a_STATEMACHINE.java @@ -26,16 +26,42 @@ public static void main(String[] args) throws IOException, ExecutionException, I final String apiClientPrefix = ApiPrefixHelper.API_DEV_CLIENT_PREFIX.getPrefix(); - Logger logger = LoggerFactory.getLogger(Task04a_STATEMACHINE.class.getName()); + Logger logger = LoggerFactory.getLogger("commercetools"); + final ProjectApiRoot client = createApiClient(apiClientPrefix); final StateMachineService stateMachineService = new StateMachineService(client); // TODO Use StateMachineService.java to create your designed order state machine // - stateMachineService.createState("mh1OrderPacked", StateTypeEnum.ORDER_STATE, true, "MH1 Order Packed") - .thenCombineAsync(stateMachineService.createState("mh1OrderShipped", StateTypeEnum.ORDER_STATE, false, "MH1 Order Shipped"), - (orderPackedStateApiResponse, orderShippedStateApiResponse)-> + stateMachineService.createState( + "mhOrderPacked1", + StateTypeEnum.ORDER_STATE, + true, + "MH Order Packed1" + ) + .exceptionally( throwable -> { + logger.error("Exception: " + throwable.getMessage()); + try { + return stateMachineService.getStateByKey("mhOrderPacked1").get(); + } + catch (Exception e){client.close();logger.error(e.getMessage());return null;} + }) + .thenCombineAsync( + stateMachineService.createState( + "mhOrderShipped1", + StateTypeEnum.ORDER_STATE, + false, + "MH Order Shipped1" + ) + .exceptionally( throwable -> { + logger.error("Exception: " + throwable.getMessage()); + try { + return stateMachineService.getStateByKey("mhOrderShipped1").get(); + } + catch (Exception e){client.close();logger.error(e.getMessage());return null;} + }), + (orderPackedStateApiResponse, orderShippedStateApiResponse) -> stateMachineService.setStateTransitions( orderPackedStateApiResponse.getBody(), Stream.of( @@ -54,11 +80,14 @@ public static void main(String[] args) throws IOException, ExecutionException, I ) .get() .thenApply(ApiHttpResponse::getBody) - .thenAccept(resource -> logger.info("State info {}",resource.getId())) - .exceptionally(exception -> { - logger.info("An error occured " + exception.getMessage()); - return null;} - ) + .handle((state, exception) -> { + if (exception == null) { + logger.info("Initial state key {}", state.getKey()); + return state; + }; + logger.error("Exception: " + exception.getMessage()); + return null; + }) .thenRun(() -> client.close()); // TODO Create an order in the Merchant Center and verify that custom workflow states are available diff --git a/src/main/java/handson/Task07b_CUSTOMOBJECTS.java b/src/main/java/handson/Task07b_CUSTOMOBJECTS.java index 0501144..160469c 100644 --- a/src/main/java/handson/Task07b_CUSTOMOBJECTS.java +++ b/src/main/java/handson/Task07b_CUSTOMOBJECTS.java @@ -49,11 +49,15 @@ public static void main(String[] args) throws IOException, ExecutionException, I .container("plants-compatibility-info") .key("tulip-seed-product") .value(tulipObject) - ) - .execute() + ).execute() .thenApply(ApiHttpResponse::getBody) - .thenAccept(resource -> logger.info("Resource ID: " + resource.getId())) - .exceptionally(exception -> { logger.info("An error occured " + exception.getMessage()); return null;}) - .thenRun(() -> client.close()); + .handle((customObject, exception) -> { + if (exception == null) { + logger.info("Custom Object ID: " + customObject.getId()); + return customObject; + } + logger.error("Exception: " + exception.getMessage()); + return null; + }).thenRun(() -> client.close()); } } diff --git a/src/main/java/handson/Task07c_APIEXTENSION.java b/src/main/java/handson/Task07c_APIEXTENSION.java index a51d931..407855a 100644 --- a/src/main/java/handson/Task07c_APIEXTENSION.java +++ b/src/main/java/handson/Task07c_APIEXTENSION.java @@ -46,12 +46,16 @@ public static void main(String[] args) throws IOException, ExecutionException, I ) .build() ) - ) - .execute() + ).execute() .thenApply(ApiHttpResponse::getBody) - .thenAccept(resource -> logger.info("Resource ID: " + resource.getId())) - .exceptionally(exception -> { logger.info("An error occured " + exception.getMessage()); return null;}) - .thenRun(() -> client.close()); + .handle((extension, exception) -> { + if (exception == null) { + logger.info("API Extension ID: " + extension.getId()); + return extension; + } + logger.error("Exception: " + exception.getMessage()); + return null; + }).thenRun(() -> client.close()); } } diff --git a/src/main/java/handson/Task08a_SUBSCRIPTION.java b/src/main/java/handson/Task08a_SUBSCRIPTION.java index ee6dabe..69793c4 100644 --- a/src/main/java/handson/Task08a_SUBSCRIPTION.java +++ b/src/main/java/handson/Task08a_SUBSCRIPTION.java @@ -56,14 +56,15 @@ public static void main(String[] args) throws IOException, ExecutionException, I .build() ) - ) - .execute() + ).execute() .thenApply(ApiHttpResponse::getBody) - .thenAccept(resource -> logger.info("Resource ID: " + resource.getId())) - .exceptionally(exception -> { - logger.info("An error occured " + exception.getMessage()); - return null;} - ) - .thenRun(() -> client.close()); + .handle((subscription, exception) -> { + if (exception == null) { + logger.info("Subscription ID: " + subscription.getId()); + return subscription; + } + logger.error("Exception: " + exception.getMessage()); + return null; + }).thenRun(() -> client.close()); } } diff --git a/src/main/java/handson/impl/ApiPrefixHelper.java b/src/main/java/handson/impl/ApiPrefixHelper.java index e17a85a..33ca92a 100644 --- a/src/main/java/handson/impl/ApiPrefixHelper.java +++ b/src/main/java/handson/impl/ApiPrefixHelper.java @@ -1,11 +1,11 @@ package handson.impl; public enum ApiPrefixHelper { - API_DEV_CLIENT_PREFIX("DEV_PREFIX"), + API_DEV_CLIENT_PREFIX("ctp."), API_TEST_CLIENT_PREFIX("TEST_PREFIX"), - API_DEV_IMPORT_PREFIX("DEV_IMPORT_PREFIX"), - API_STORE_CLIENT_PREFIX("DEV_STORE_PREFIX"), - API_ME_CLIENT_PREFIX("DEV_ME_PREFIX"), + API_DEV_IMPORT_PREFIX("ctp-import."), + API_STORE_CLIENT_PREFIX("ctp-boston."), + API_ME_CLIENT_PREFIX("ctp-me."), API_STORE_ME_CLIENT_PREFIX("DEV_STORE_ME_PREFIX"); private final String prefix; diff --git a/src/main/java/handson/impl/ClientService.java b/src/main/java/handson/impl/ClientService.java index dc9fb7b..8f0f59d 100644 --- a/src/main/java/handson/impl/ClientService.java +++ b/src/main/java/handson/impl/ClientService.java @@ -23,7 +23,23 @@ public class ClientService { */ public static ProjectApiRoot createApiClient(final String prefix) throws IOException { - projectApiRoot = null; + final Properties prop = new Properties(); + prop.load(ClientService.class.getResourceAsStream("/dev.properties")); + String clientId = prop.getProperty(prefix + "clientId"); + String clientSecret = prop.getProperty(prefix + "clientSecret"); + String projectKey = prop.getProperty(prefix + "projectKey"); + + projectApiRoot = ApiRootBuilder.of() + .defaultClient( + ClientCredentials.of() + .withClientId(clientId) + .withClientSecret(clientSecret) + .build(), + ServiceRegion.GCP_EUROPE_WEST1.getOAuthTokenUrl(), + ServiceRegion.GCP_EUROPE_WEST1.getApiUrl() + ) + .build(projectKey); + return projectApiRoot; } diff --git a/src/main/java/handson/impl/StateMachineService.java b/src/main/java/handson/impl/StateMachineService.java index 158fc2b..d4217f8 100644 --- a/src/main/java/handson/impl/StateMachineService.java +++ b/src/main/java/handson/impl/StateMachineService.java @@ -19,6 +19,15 @@ public StateMachineService(final ProjectApiRoot client) { this.apiRoot = client; } + public CompletableFuture> getStateByKey(final String key) { + + return + apiRoot + .states() + .withKey(key) + .get() + .execute(); + } public CompletableFuture> createState(final String key, StateTypeEnum stateTypeEnum, final Boolean initial, final String name) { Map myNames = new HashMap() {