### Install Java SDK with Gradle Source: https://github.com/commercetools/commercetools-sdk-java-v2/blob/main/README.md Add the commercetools SDK dependencies to your Gradle project. Ensure you have mavenCentral() repository configured. ```gradle ext { versions = [ commercetools: "19.11.0" ] } sourceCompatibility = 11 repositories { mavenCentral() } dependencies { implementation "com.commercetools.sdk:commercetools-http-client:${versions.commercetools}" implementation "com.commercetools.sdk:commercetools-sdk-java-api:${versions.commercetools}" implementation "com.commercetools.sdk:commercetools-sdk-java-importapi:${versions.commercetools}" } ``` -------------------------------- ### Install Java SDK with Maven Source: https://github.com/commercetools/commercetools-sdk-java-v2/blob/main/README.md Include the commercetools SDK dependencies in your Maven project's pom.xml. The version is defined in the properties section. ```maven 19.11.0 com.commercetools.sdk commercetools-http-client ${commercetools.version} com.commercetools.sdk commercetools-sdk-java-api ${commercetools.version} com.commercetools.sdk commercetools-sdk-java-importapi ${commercetools.version} ``` -------------------------------- ### Configure Retry Logic in 2.x Source: https://github.com/commercetools/commercetools-sdk-java-v2/blob/main/Migration.md Version 2.x allows setting up retry policies directly during client creation using the RetryMiddleware. This example demonstrates configuring max retries and status codes for retries. ```java final ByProjectKeyRequestBuilder projectClient = ApiRootBuilder.of() .defaultClient(ServiceRegion.GCP_EUROPE_WEST1.getApiUrl(), ClientCredentials.of().withClientId("clientId").withClientSecret("clientSecret").build(), ServiceRegion.GCP_EUROPE_WEST1.getOAuthTokenUrl()) .withPolicies( policyBuilder -> policyBuilder.withRetry(retry -> retry.maxRetries(5) .statusCodes(Arrays.asList(BAD_GATEWAY_502, SERVICE_UNAVAILABLE_503, GATEWAY_TIMEOUT_504)))) .buildForProject("projectKey"); final CategoryPagedQueryResponse body = projectClient.categories().get().executeBlocking().getBody(); ``` -------------------------------- ### Configure Retry Logic in 1.x Source: https://github.com/commercetools/commercetools-sdk-java-v2/blob/main/Migration.md In version 1.x, retry rules and the SphereClient must be defined separately before executing a request. This example shows how to configure retry rules for specific status codes. ```java final int maxAttempts = 5; final List retryRules = singletonList(RetryRule.of( RetryPredicate.ofMatchingStatusCodes(BAD_GATEWAY_502, SERVICE_UNAVAILABLE_503, GATEWAY_TIMEOUT_504), RetryAction.ofExponentialBackoff(maxAttempts, 100, 2000))); final SphereClient client = RetrySphereClientDecorator.of(sphereClient(), retryRules); final PagedQueryResult categoryPagedQueryResult = client.execute(CategoryQuery.of()) .toCompletableFuture() .get(); ``` -------------------------------- ### Handle API Errors with Exception Handling Source: https://github.com/commercetools/commercetools-sdk-java-v2/blob/main/Best-practices.md Implement error handling for API requests using exceptionally blocks. This example shows how to catch specific exceptions like BadRequestException and general ApiHttpException to access error details. ```java apiRoot.products().post(draft).execute() .exceptionally(throwable -> { if (throwable instanceof com.commercetools.api.client.error.BadRequestException) { ((BadRequestException) throwable).getErrorResponse().getMessage(); } if (throwable instanceof ApiHttpException) { ((ApiHttpException) throwable).getBodyAs(ErrorResponse.class).getMessage(); } return null; }); } ``` -------------------------------- ### Create Category Command (1.x vs 2.x) Source: https://github.com/commercetools/commercetools-sdk-java-v2/blob/main/Migration.md Illustrates the difference in creating a category draft and executing the create command between SDK v1 and v2. ```java LocalizedString name = LocalizedString.ofEnglish("name"); LocalizedString slug = LocalizedString.ofEnglish("slug"); CategoryDraft categoryDraft = CategoryDraftBuilder.of(name, slug).build(); Category category = blockingClient().executeBlocking(CategoryCreateCommand.of(categoryDraft)); ``` ```java String en = Locale.ENGLISH.toLanguageTag(); LocalizedString name = LocalizedStringBuilder.of().addValue(en, "name").build(); LocalizedString slug = LocalizedStringBuilder.of().addValue(en, "slug").build(); CategoryDraft categoryDraft = CategoryDraftBuilder.of().name(name).slug(slug).build(); Category category = projectClient().categories().post(categoryDraft).executeBlocking().getBody(); ``` -------------------------------- ### Create Client: SDK v1 vs SDK v2 Source: https://github.com/commercetools/commercetools-sdk-java-v2/blob/main/Migration.md Illustrates the change in client creation from SphereClientFactory in v1 to ApiRootBuilder in v2. The v2 approach simplifies request creation directly from the ApiRootBuilder. ```java final SphereClient sphereClient = SphereClientFactory.of() .createClient("projectKey", "clientId", "clientSecret"); ``` ```java final ProjectApiRoot projectRoot = ApiRootBuilder.of() .defaultClient(ClientCredentials.of().withClientId("clientId").withClientSecret("clientSecret").build(), ServiceRegion.GCP_EUROPE_WEST1.getOAuthTokenUrl(), ServiceRegion.GCP_EUROPE_WEST1.getApiUrl()) .build("projectKey"); ``` -------------------------------- ### Configure HTTP Client with Proxy Source: https://github.com/commercetools/commercetools-sdk-java-v2/blob/main/Best-practices.md Set up an HTTP client with proxy configuration for SDK requests. This is useful when your application needs to route traffic through a proxy server. ```java Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy", 8080)); VrapHttpClient httpClient = new CtOkHttp4Client(builder -> builder.proxy(proxy)); ApiRoot apiRoot = ApiRootBuilder.of(httpClient) .defaultClient(ClientCredentials.of() .withClientId("your-client-id") .withClientSecret("your-client-secret") .withScopes("your-scopes") .build(), ServiceRegion.GCP_EUROPE_WEST1) .build(); ``` -------------------------------- ### Query Categories (1.x vs 2.x) Source: https://github.com/commercetools/commercetools-sdk-java-v2/blob/main/Migration.md Compares the query structure for categories, showing the use of .get(), .withWhere(), and .withPredicateVar() in v2. ```java PagedQueryResult pagedQueryResult = blockingClient() .executeBlocking(CategoryQuery.of().byId("id123")); ``` ```java CategoryPagedQueryResponse response = projectClient().categories() .get() .withWhere("id = :id") .withPredicateVar("id", "id123") .executeBlocking() .getBody(); ``` -------------------------------- ### Set Timeout: SDK v1 vs SDK v2 Source: https://github.com/commercetools/commercetools-sdk-java-v2/blob/main/Migration.md Shows how to set timeouts for blocking requests. SDK v1 uses a separate method parameter, while SDK v2 integrates it directly into the executeBlocking method. ```java PagedQueryResult response = blockingClient().executeBlocking(CategoryQuery.of(), 45, TimeUnit.SECONDS); ``` ```java CategoryPagedQueryResponse response = projectClient().categories() .get() .executeBlocking(Duration.ofSeconds(45)) .getBody(); ``` -------------------------------- ### Configure UserAgentMiddleware Source: https://github.com/commercetools/commercetools-sdk-java-v2/blob/main/Best-practices.md Adds a User-Agent header to every request. Can be configured using the defaultClient builder or customized directly. ```java ApiRootBuilder.of().withUserAgentSupplier(() -> "my-custom-useragent"); ``` -------------------------------- ### Configure OAuthMiddleware with Client Credentials Flow Source: https://github.com/commercetools/commercetools-sdk-java-v2/blob/main/Best-practices.md Adds an authentication token to requests and automatically reauthenticates. Use the defaultClient builder for the client credentials flow. ```java ApiRootBuilder.of().withOAuthMiddleware( OAuthMiddleware.of( new OAuthHandler( new InMemoryTokenSupplier( ... ) ) ) ) ``` ```java ApiRootBuilder.of().withClientCredentialsFlow( ClientCredentials.of().build(), ServiceRegion.GCP_EUROPE_WEST1.getOAuthTokenUrl() ); ``` -------------------------------- ### Query Category By ID (1.x vs 2.x) Source: https://github.com/commercetools/commercetools-sdk-java-v2/blob/main/Migration.md Highlights the change in fetching a category by ID, using the .get() method and .withExpand() in v2. ```java Category loadedCategory = blockingClient() .executeBlocking(CategoryByIdGet.of(category.getId()).withExpansionPaths(m -> m.parent())); ``` ```java Category queriedCategory = projectClient().categories() .withId(category.getId()) .get() .withExpand("parent") .executeBlocking() .getBody(); ``` -------------------------------- ### Create Category From JSON (1.x vs 2.x) Source: https://github.com/commercetools/commercetools-sdk-java-v2/blob/main/Migration.md Shows the change in JSON deserialization for creating a category, replacing SphereJsonUtils with JsonUtils. ```java final CategoryDraft categoryDraft = SphereJsonUtils.readObjectFromResource("category.json", CategoryDraft.class); final Category category = blockingClient().executeBlocking(CategoryCreateCommand.of(categoryDraft)); ``` ```java final CategoryDraft categoryDraft = JsonUtils.fromJsonString(TestUtils.stringFromResource("category.json"), CategoryDraft.class); final Category category = projectClient().categories().post(categoryDraft).executeBlocking().getBody(); ``` -------------------------------- ### Create Category Draft in 1.x Source: https://github.com/commercetools/commercetools-sdk-java-v2/blob/main/Migration.md The 1.x version uses a builder pattern with explicit methods for each field, including LocalizedString creation. ```java LocalizedString name = LocalizedString.ofEnglish("name"); LocalizedString slug = LocalizedString.ofEnglish("slug"); LocalizedString metaDescription = LocalizedString.ofEnglish("metaDescription"); LocalizedString metaTitle = LocalizedString.ofEnglish("metaTitle"); LocalizedString metaKeywords = LocalizedString.ofEnglish("metaKeywords"); CategoryDraft categoryDraft = CategoryDraftBuilder.of(name, slug) .metaDescription(metaDescription) .metaTitle(metaTitle) .metaKeywords(metaKeywords) .externalId("externalId") .build(); ``` -------------------------------- ### Update Category Command (1.x vs 2.x) Source: https://github.com/commercetools/commercetools-sdk-java-v2/blob/main/Migration.md Demonstrates the updated approach to creating update actions for a category, using CategoryUpdateBuilder in v2. ```java LocalizedString newName = LocalizedString.ofEnglish("new name"); CategoryUpdateCommand command = CategoryUpdateCommand.of(category, Collections.singletonList(ChangeName.of(newName))); Category updatedCategory = blockingClient().executeBlocking(command); ``` ```java LocalizedString newName = LocalizedStringBuilder.of().addValue("en", "new name").build(); CategoryUpdate categoryUpdate = CategoryUpdateBuilder.of() .version(category.getVersion()) .actions(CategoryChangeNameActionBuilder.of().name(newName).build()) .build(); Category updatedCategory = projectClient().categories() .withId(category.getId()) .post(categoryUpdate) .executeBlocking() .getBody(); ``` -------------------------------- ### Add Header: SDK v2 Source: https://github.com/commercetools/commercetools-sdk-java-v2/blob/main/Migration.md Demonstrates how to add custom headers to a request in SDK v2 using the addHeader method. This is a direct way to set headers compared to SDK v1. ```java final CartPagedQueryResponse carts = projectClient().carts() .get() .addHeader("foo", "bar") .executeBlocking() .getBody(); ``` -------------------------------- ### Reuse the Client Instance Source: https://github.com/commercetools/commercetools-sdk-java-v2/blob/main/Best-practices.md Create the ApiRoot object instance once and reuse it throughout the application for efficiency. ```java ProjectApiRoot apiRoot = ApiRootBuilder.of() .defaultClient(ClientCredentials.of() .withClientId("your-client-id") .withClientSecret("your-client-secret") .withScopes("your-scopes") .build(), ServiceRegion.GCP_EUROPE_WEST1) .build("your-project-key"); ``` -------------------------------- ### Create Product with Multiple Variants Source: https://github.com/commercetools/commercetools-sdk-java-v2/blob/main/Best-practices.md Define a ProductDraft with multiple variants, each having a unique SKU and attributes. This is the standard way to create products with variations in the SDK. ```java ProductDraft draft = ProductDraft.builder() .productType(builder -> builder.key("show")) .name(LocalizedStringBuilder.of().addValue("en", "foo").build()) .slug(LocalizedStringBuilder.of().addValue("en", "foo").build()) .plusVariants(builder -> builder.sku("abc").plusAttributes(attributeBuilder -> attributeBuilder.name("size").value("32"))) .plusVariants(builder -> builder.sku("sku").plusAttributes(attributeBuilder -> attributeBuilder.name("size").value("32"))) .build(); Product product = apiRoot.products().post(draft).executeBlocking().getBody(); ``` -------------------------------- ### Customize the HTTP Client Source: https://github.com/commercetools/commercetools-sdk-java-v2/blob/main/Best-practices.md Provide a custom VrapHttpClient instance to the builder for additional HTTP client customization, such as setting timeouts and connection limits. ```java VrapHttpClient httpClient = new CtOkHttp4Client( 128, // maxRequests 128, // maxRequestsPerHost builder -> builder.connectTimeout(Duration.ofMillis(200)) .writeTimeout(Duration.ofSeconds(60)) .readTimeout(Duration.ofSeconds(120))); ProjectApiRoot apiRoot = ApiRootBuilder.of(httpClient) .defaultClient(ClientCredentials.of() .withClientId("your-client-id") .withClientSecret("your-client-secret") .withScopes("your-scopes") .build(), ServiceRegion.GCP_EUROPE_WEST1) .build("my-project"); ``` -------------------------------- ### Configure NotFoundExceptionMiddleware Source: https://github.com/commercetools/commercetools-sdk-java-v2/blob/main/Best-practices.md Prevents NotFoundException by returning null when a resource is not found. Can be limited to specific HTTP methods or request predicates. ```java ApiRootBuilder.of().addNotFoundExceptionMiddleware(); ``` ```java ApiRootBuilder.of().addNotFoundExceptionMiddleware(Collections.singleton(ApiHttpMethod.GET)); ``` ```java ApiRootBuilder.of().addNotFoundExceptionMiddleware(request -> request.getUri().getPath().contains("products")); ``` -------------------------------- ### Custom ErrorMiddleware Configuration Source: https://github.com/commercetools/commercetools-sdk-java-v2/blob/main/Best-practices.md Shows custom configuration of ErrorMiddleware, equivalent to the default method. Ensures ErrorMiddleware is the last in the call stack. ```java ApiRootBuilder.of().withErrorMiddleware(ErrorMiddleware.of(HttpExceptionFactory.of(ResponseSerializer.of()))); ``` -------------------------------- ### Configure ErrorMiddleware with ApiRootBuilder Source: https://github.com/commercetools/commercetools-sdk-java-v2/blob/main/Best-practices.md Use ApiRootBuilder to configure the ErrorMiddleware. This middleware translates HTTP errors into Exceptions. ```java ApiRootBuilder.of().withErrorMiddleware(); ``` -------------------------------- ### Configure InternalLoggerMiddleware Source: https://github.com/commercetools/commercetools-sdk-java-v2/blob/main/Best-practices.md Logs request and response details, including URL, method, status code, timing, and correlation ID. Use Debug or Trace levels for payload and header details. Sensitive information is redacted. ```java ApiRootBuilder.of().withInternalLoggerMiddleware(InternalLoggerMiddleware.of(ApiInternalLoggerFactory::get)); ``` -------------------------------- ### Create Category Draft in 2.x Source: https://github.com/commercetools/commercetools-sdk-java-v2/blob/main/Migration.md Version 2.x simplifies LocalizedString creation and uses a more fluent builder pattern for CategoryDraft. The LocalizedStringBuilder is used for creating localized strings. ```java String en = Locale.ENGLISH.toLanguageTag(); LocalizedString name = LocalizedStringBuilder.of().addValue(en, "name").build(); LocalizedString slug = LocalizedStringBuilder.of().addValue(en, "slug").build(); LocalizedString metaDescription = LocalizedStringBuilder.of().addValue(en, "metaDescription").build(); LocalizedString metaTitle = LocalizedStringBuilder.of().addValue(en, "metaTitle").build(); LocalizedString metaKeywords = LocalizedStringBuilder.of().addValue(en, "metaKeywords").build(); CategoryDraft categoryDraft = CategoryDraftBuilder.of() .name(name) .slug(slug) .externalId("externalId") .metaTitle(metaTitle) .metaDescription(metaDescription) .metaKeywords(metaKeywords) .build(); ``` -------------------------------- ### Configure PolicyMiddleware for Retries Source: https://github.com/commercetools/commercetools-sdk-java-v2/blob/main/Best-practices.md Combines policies for failing requests, allowing retries on specific HTTP status codes or exception types. Configure max retries and target status codes. ```java ApiRootBuilder.of().withPolicies(policyBuilder -> policyBuilder.withRetry(retry -> retry.maxRetries(3) .statusCodes(Arrays.asList(HttpStatusCode.SERVICE_UNAVAILABLE_503, HttpStatusCode.INTERNAL_SERVER_ERROR_500)))) ``` -------------------------------- ### Configure ConcurrentModificationMiddleware Source: https://github.com/commercetools/commercetools-sdk-java-v2/blob/main/Best-practices.md Retries requests upon concurrent modification errors by updating the resource version. Configure the number of retries. ```java ApiRootBuilder.of().withMiddleware(ConcurrentModificationMiddleware.of(3)); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.