Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

updated sdk version to 17.4 #33

Open
wants to merge 25 commits into
base: solutions
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 8 additions & 6 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@ plugins {

ext {
versions = [
commercetools: "14.5.0",
slf4j: "1.7.36",
logback: "1.2.10",
commercetools: "17.17.0",
slf4j: "2.0.13",
logback: "1.4.12",
]
}

Expand All @@ -44,11 +44,11 @@ repositories {
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-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 "com.commercetools.sdk:commercetools-graphql-api:${versions.commercetools}"
implementation "org.slf4j:slf4j-api:${versions.slf4j}"
implementation "ch.qos.logback:logback-classic:${versions.logback}"
implementation group: 'com.googlecode.json-simple', name: 'json-simple', version: '1.1.1'

// implementation group: 'org.slf4j', name: 'slf4j-log4j12', version: '2.0.0-alpha0'

Expand All @@ -57,7 +57,9 @@ dependencies {
// implementation 'com.commercetools.sdk.jvm.core:commercetools-models:1.53.0'
// implementation 'com.commercetools.sdk.jvm.core:commercetools-java-client:1.53.0'

implementation group: 'org.json', name: 'json', version: '20200518'
implementation group: 'org.json', name: 'json', version: '20231013'
implementation 'javax.json:javax.json-api:1.1.4'
implementation 'org.glassfish:javax.json:1.1.4'

implementation 'io.aexp.nodes.graphql:nodes:0.4.0-atlassian-hosted'
}
108 changes: 108 additions & 0 deletions src/main/java/handson/Task01a_GET_QUERY.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
package handson;

import com.commercetools.api.client.ProjectApiRoot;
import com.commercetools.api.models.project.Project;
import com.commercetools.api.models.tax_category.TaxCategory;
import com.commercetools.api.models.tax_category.TaxCategoryPagedQueryResponse;
import com.fasterxml.jackson.core.JsonProcessingException;
import handson.impl.ApiPrefixHelper;
import io.vrap.rmf.base.client.ApiHttpResponse;
import io.vrap.rmf.base.client.error.NotFoundException;
import io.vrap.rmf.base.client.utils.json.JsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;

import static handson.impl.ClientService.createApiClient;


public class Task01a_GET_QUERY {

public static void main(String[] args) throws IOException, ExecutionException, InterruptedException {

final String apiClientPrefix = ApiPrefixHelper.API_DEV_CLIENT_PREFIX.getPrefix();

try (ProjectApiRoot apiRoot = createApiClient(apiClientPrefix)) {

Logger logger = LoggerFactory.getLogger("commercetools");

// TODO: GET project info
//

Project project = apiRoot.get().executeBlocking().getBody();
logger.info("Project key: {}", project.getKey());

// TODO CHECK if a Shipping Method exists
//
try {
int statusCode = apiRoot.shippingMethods()
.withKey("standard")
.head()
.executeBlocking().getStatusCode();
logger.info("Response: " + statusCode);
}
catch (NotFoundException nfe) {
logger.info("Shipping method not found " + nfe.getStatusCode());
}
catch (Exception e) {
logger.info("Shipping method not found " + e.getMessage());
}

// TODO CHECK if a Shipping Method exists asynchronously
//
apiRoot.shippingMethods()
.withKey("standard-delivery")
.head()
.execute()
.thenAccept((apiHttpResponse) -> {
int statusCode = apiHttpResponse.getStatusCode();
logger.info("Response: " + statusCode);
})
.exceptionally(throwable -> {logger.info("Shipping method not found " + throwable.getMessage());
return null;
}).join();


// TODO: GET tax categories
//

TaxCategoryPagedQueryResponse taxCategoryPagedQueryResponse = apiRoot
.taxCategories()
.get()
.executeBlocking().getBody();
if (taxCategoryPagedQueryResponse != null && taxCategoryPagedQueryResponse.getResults() != null) {
logger.info("Tax categories: {}",
taxCategoryPagedQueryResponse.getResults()
.stream()
.map(TaxCategory::getKey)
.collect(Collectors.toList())
);
} else {
logger.warn("No tax categories found.");
}


// TODO Get Tax category by Key
//
apiRoot.taxCategories()
.withKey("standard-tax")
.get()
.execute()
.thenApply(ApiHttpResponse::getBody)
.thenAccept(taxCategory -> {
logger.info("Tax category ID: {}", taxCategory.getId());
try {
System.out.println(JsonUtils.prettyPrint(JsonUtils.toJsonString(taxCategory)));
} catch (JsonProcessingException ignored) { }
})
.exceptionally(throwable -> {
logger.error("Exception: {}", throwable.getMessage());
return null;
}).join();

}
}
}
63 changes: 0 additions & 63 deletions src/main/java/handson/Task02a_CREATE.java

This file was deleted.

87 changes: 87 additions & 0 deletions src/main/java/handson/Task02a_PRODUCT_SEARCH.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
package handson;

import com.commercetools.api.client.ProjectApiRoot;
import com.commercetools.api.models.category.Category;
import com.commercetools.api.models.product.*;
import handson.impl.ApiPrefixHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.stream.Collectors;

import static handson.impl.ClientService.createApiClient;

public class Task02a_PRODUCT_SEARCH {

public static void main(String[] args) throws Exception {

// TODO UPDATE: Product projection in Store
final String apiClientPrefix = ApiPrefixHelper.API_DEV_CLIENT_PREFIX.getPrefix();

try (ProjectApiRoot apiRoot = createApiClient(apiClientPrefix)) {
Logger logger = LoggerFactory.getLogger("commercetools");

Category furnitureCategory = apiRoot.categories()
.withKey("home-decor")
.get()
.execute().get().getBody();

// filter from product projection query response

// the effective filter from the search response
// params found in the product projection search https://docs.commercetools.com/api/projects/products-search#search-productprojections
ProductProjectionPagedSearchResponse productProjectionPagedSearchResponse = apiRoot
// TODO Get all products
.productProjections().search()
.get()
.withStaged(false)

// TODO Restrict on category home-decor
.withMarkMatchingVariants(true)
.withFilterQuery("categories.id:\"" + furnitureCategory.getId() + "\"")

// TODO Get all Facets for Enum color and finish
// Make sure the attributes are searchable

.withFacet("variants.attributes.color.en-US as Color-EN")
.addFacet("variants.attributes.color.de-DE as Color-DE")
.addFacet("variants.attributes.finish.en-US as Finish-EN")
.addFacet("variants.attributes.finish.de-DE as Finish-DE")
.addFacet("variants.price.centAmount:range (1000 to 10000),(10000 to 100000),(100000 to *) as Prices")

// TODO Give price range on products with no effect on facets
// .withFilter("variants.price.centAmount:range (1000 to 100000)")

// TODO: with effect on facets
// .addFilterQuery("variants.price.centAmount:range (1000 to 100000)")
// .addFilterQuery("variants.attributes.color.en-US:\"Golden Rod:#DAA520\"")

// TODO: Simulate click on facet White:#FFFFFF or Golden Rod:#DAA520 from attribute color
// .withFilterFacets("variants.attributes.color.en-US:\"Golden Rod:#DAA520\"")
.executeBlocking()
.getBody();

int size = productProjectionPagedSearchResponse.getResults().size();
logger.info("No. of products: " + size);
List<ProductProjection> result = productProjectionPagedSearchResponse.getResults().subList(0, size);
System.out.println("products searched: ");
result.forEach((r) -> System.out.println(r.getKey()));

logger.info("Facet count: " + productProjectionPagedSearchResponse.getFacets().values().size());
logger.info("Facets: " + productProjectionPagedSearchResponse.getFacets().values().keySet());
for (String facet: productProjectionPagedSearchResponse.getFacets().values().keySet()){
FacetResult facetResult = productProjectionPagedSearchResponse.getFacets().withFacetResults(FacetResultsAccessor::asFacetResultMap).get(facet);
if (facetResult instanceof RangeFacetResult) {
logger.info("{} ranges: {}", facet ,((RangeFacetResult)facetResult).getRanges().size());
logger.info("Facet counts: {}", ((RangeFacetResult)facetResult).getRanges().stream().map(facetResultRange -> facetResultRange.getFromStr() + " to " + facetResultRange.getToStr() + ": " + facetResultRange.getCount()).collect(Collectors.toList()));
}
else if (facetResult instanceof TermFacetResult) {
logger.info("{} terms: {}", facet, ((TermFacetResult)facetResult).getTerms().size());
logger.info("Facet counts: {}", ((TermFacetResult)facetResult).getTerms().stream().map(facetResultTerm -> facetResultTerm.getTerm() + ": " + facetResultTerm.getCount()).collect(Collectors.joining(", ")));
}
}

}
}
}
52 changes: 52 additions & 0 deletions src/main/java/handson/Task02b_CREATE.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package handson;

import com.commercetools.api.client.ProjectApiRoot;
import handson.impl.ApiPrefixHelper;
import handson.impl.ClientService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.concurrent.ExecutionException;

import static handson.impl.ClientService.createApiClient;


/**
* Configure sphere client and get project information.
*
* See:
* TODO dev.properties
* TODO {@link ClientService#createApiClient(String prefix)}
*/
public class Task02b_CREATE {

public static void main(String[] args) throws IOException, ExecutionException, InterruptedException {

final String apiClientPrefix = ApiPrefixHelper.API_DEV_CLIENT_PREFIX.getPrefix();
try (ProjectApiRoot apiRoot = createApiClient(apiClientPrefix)) {

Logger logger = LoggerFactory.getLogger("commercetools");

// TODO: CREATE a Category
//

apiRoot.categories()
.create(
cb -> cb
.key("clearance")
.name(lsb -> lsb.addValue("en-US", "Clearance"))
.slug(lsb -> lsb.addValue("en-US", "clearance-sale-summer"))
)
.execute()
.thenAccept(categoryApiHttpResponse ->
logger.info("Category created: {}",
categoryApiHttpResponse.getBody().getId())
)
.exceptionally(throwable -> {
logger.error("Exception: {}", throwable.getMessage());
return null;
}).join();
}
}
}
Loading